我正在制作一项服务,该服务从远程主机检索照片并在将其传递给客户端之前进行一些处理。它会在本地缓存检索到的源照片,以避免以后再次检索它。
但是,如果快速连续有多个请求,则源图像尚未在本地保存,并且会执行不必要的检索。
在将源图像缓存之前,将传入的请求推迟到有什么好方法,前提是它当前已被检索?
我目前正在从入站请求流中一直使用Node.js流,将其传递给我的缓存和转换逻辑,并将其传递给出站流。
答案 0 :(得分: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
将返回相同的承诺,当承诺得到解决时,两个请求都会得到相同的响应。