我正在尝试使用node.js为不同客户端的数据传输工具实现一个缓存系统。 这是一个 http 服务,我使用 Express 来处理请求。我的缓存系统需要支持三种情况:
情况 1 - 没有缓存: 程序通过给定的 get 方法接收数据。如果成功,它将写入缓存。
情况 2 - 有缓存: 程序接收缓存。
情况 3 - 没有缓存,但同一请求的 get 方法已被不同的客户端调用并且当前正在处理。 程序需要等待,直到另一个请求通过 get 方法收到其数据并交付新写入的缓存。
我用事件解决了“案例3”的问题。我为每个客户/请求组合注册一个事件。但注册大量事件感觉不太优雅。此外,使用队列并不是最好的解决方案之一。
最佳答案
在我看来,您不需要事件来实现缓存系统,但我不知道如何在没有队列的情况下实现它。
这是我实现缓存的方法:
var cache = {};
function get(uri, cb) {
var key = uri; // id of the resource, you might want to strip some URI parts
var cacheEntry = cache[key];
if (!cacheEntry)
cache[key] = cacheEntry = {};
if (cacheEntry.value) {
// cache hit - return the cached value
return process.nextTick(function() { cb(null, cacheEntry.value });
}
if (cacheEntry.waiting) {
// another request is in progress - queue the callback
cacheEntry.waiting.push(cb);
return;
}
// we are the first client asking for this value
cacheEntry.waiting = [cb];
request.get(uri, handleResponse);
function handleResponse(err, resp, body) {
// process the response headers and body and save it to the cache
var content = body;
cacheEntry.value = content;
// fire callbacks waiting for the cached value
if (cacheEntry.waiting) {
var q = cacheEntry.waiting;
delete cacheEntry.waiting;
q.forEach(function(cb) { cb(null, content); })
}
}
}
关于javascript - 在node.js中强制x客户端等待客户端y的回调的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310078/