如何在node.js中创build一个caching,该caching明确处理CPU绑定操作的同时重复请求

所以节点对我来说很好。 我有一个非常特定的服务器应用程序,基本上接受执行特定的CPU绑定过程的请求,并执行一个C程序来这样做。 事情是,如果我有多个客户端,很可能我会得到相同请求的多个版本。 这将是一个很好的优化,以某种方式明确地处理,通过实现一个caching与一个特定的关键锁,使其他客户端将简单地等待这个请求回来,并复制其响应。

但我是新来的节点,所以我不知道如何将这个绑定到我的基本节点路由器请求处理机制。 显然,我可以用语言x来使用基本的并发原语,但是我知道这个节点是面向事件的,我认为这可以用一种平凡的方式完成。 想法?

上面有几个答案,但没有一个真正地把对同一个资源的请求正确地对待。

因为节点是单线程环境,所以在检查caching键时不需要担心并发性。 你所有的行为都是primefaces的。 节点中的所有asynchronous操作都会导致它接受更多的请求。 因此,你需要处理并发的重叠请求,这里解决了注册观察员到EventEmmiter:

var http = require('http'), EventEmitter = require('events').EventEmitter; var cache = {}; http.createServer(function (req, res) { var key = someMagic(req), cached = cache[key]; // get some unique request identifier if (!cached) { // if we've never seen this request before cached = new EventEmitter(); // make this cache entry an event emitter cached.status = 'running'; handleAsyncRequest(function(result) { // your request handling is probably asynchronous, call this callback when you're done cached.response = result; // memoize data cached.status = 'finished'; cached.emit('finished'); // notify all observers waiting for this request }); } else { switch(cached.status) { // if existing request, check if it's still running or finished case 'finished': res.end(cached.response); // send cached response immediately if request has finished break; case 'running': // subscribe as observer; send response when request is finished cached.once('finished', function() { res.end(cached.response); }); break; } } }).listen(1337, "127.0.0.1"); 

在JavaScript的客户端世界中,您通常将项目caching在数组中。 我也是一个新的节点,所以请原谅,如果这不是你正在寻找的答案,但值得一试。

您可以在服务器启动时设置一个空数组,并根据收到的请求将结果存储为特定的散列。 这似乎是一个可行的解决scheme。

例如

 var http = require('http'); var cache = []; http.createServer(function (req, res) { var obj; if(!cache[key]) { obj = .... // logic that gets results cache[obj.key] = obj; } else { obj = cache[key]; } }).listen(1337, "127.0.0.1"); 

容易peasy .. Node.js是单线程,所以第一个CPU绑定请求无论如何阻塞服务器..所以记忆结果。 本质上,你用请求的键设置一个散列,在调用C程序之前,检查散列。 如果在那里,把它归还,你就完成了。 如果不是这样,运行C程序,在返回之前,将结果保存在所请求的密钥的哈希中, 然后返回。