2017-06-03 50 views
1

我做了一项服务,它从远程主机获取照片并在将其传递给客户端之前执行一些处理。它将检索到的源照片本地缓存,以避免以后再次检索。推迟Node.js HTTP请求,如果类似的工作已经完成

但是,如果快速连续发出多个请求,源图像将不会保存在本地,并且会执行不必​​要的检索。

如果它已经被检索到,那么推迟传入请求直到源图像被缓存为止的好方法是什么?

我目前使用Node.js流从入站请求流,通过我的缓存和转换逻辑,传递给出站流。

回答

2

您可以缓存承诺,以便所有到同一资源的传入请求只需要一次旅程,避免泛滥数据库或某些API。

const Cache = {}; 

function getPhoto(photoId) { 

    let cacheKey = `photo-${photoId}`; 
    let photoCache = Cache[cacheKey]; 

    if (photoCache instanceof Promise) 
     return photoCache; //Return the promise from the cache 

    let promise = new Promise((resolve, reject) => { 

     if (photoCache) //Return the photo if exists in cache. 
      return resolve(photoCache); 

     return processPhoto(photoId).then(response => { 
      //Override the promise with the actual response 
      Cache[cacheKey] = response; 
      resolve(response); 

     }).catch(err => { 
      Cache[cacheKey] = null; //We don't want the rejected promise in cache! 
      reject(); 
     }); 

    }); 

    if (!photoCache) 
     Cache[cacheKey] = promise; //Save the promise  

    return promise; 
} 

function processPhoto(photoId){ 

return new Promise((resolve, reject) => { 

     // Get the image from somewhere... 
     // Process it or whatever you need 

     //... 
     resolve('someResponse'); 
}); 

} 
  • 到一个特定的照片首先请求将执行查找,并存储在缓存中的承诺。
  • 第二个请求进入,如果第一个请求的照片尚未检索到,getPhoto将返回相同的承诺,当承诺解决后,两个请求都会得到相同的响应。
  • 第三个请求是在照片已经被检索后发出的,因为照片被缓存了,它只会返回响应。
+1

我使用这种技术实现它,它工作!谢谢! – sune

+0

@sune如果它有效,不要忘记将它标记为已接受的答案,以此来帮助他人。 –