For some user requests, I need to do some heavy computations (taking about 100ms of time); and, of course, I do not want to perform these in node's main event loop so that it will prevent other requests from serving.
对于某些用户请求,我需要进行一些繁重的计算(大约需要100毫秒的时间);当然,我不想在节点的主事件循环中执行这些操作,因此它会阻止其他请求的服务。
The most obvious, but definitely not the cleanest way to solve this problem would be to offload the computations to another program and wait for the results asynchronously.
解决这个问题最明显但绝对不是最干净的方法是将计算卸载到另一个程序并异步等待结果。
Is there any way to do it without leaving the node process (and implementing inter-process communications)? E.g. something like this:
没有离开节点进程(并实现进程间通信)有没有办法做到这一点?例如。像这样的东西:
var compute = function (input) {
var i,
result = input;
for (i = 0; i < 1000000; i++) {
result = md5(result);
}
}
var controller = function (req, res) {
offload(compute, req.params.input, function(result) {
res.send(result);
});
}
2 个解决方案
#1
3
I found a compute-cluster
module, which seems to be designed exactly for my goals. It spawns children processes, and the communication is made with IPC (no sockets wasted).
我发现了一个计算集群模块,它似乎完全符合我的目标。它产生子进程,并且使用IPC进行通信(没有浪费套接字)。
#2
1
The JavaScript language has no support for threads and node.js provides no interface to them either so you'll need to rely on a library to provide threading functionality. See the node-fibers and node-threads-a-go-go libraries for possible solutions.
JavaScript语言不支持线程和node.js也不提供任何接口,因此您需要依赖库来提供线程功能。有关可能的解决方案,请参阅node-fibers和node-threads-a-go-go库。
If you're looking for a way to make IPC a little easier in node.js then consider using the zeromq library (node.js bindings). This somewhat-related-answer might be useful as well.
如果您正在寻找一种在node.js中使IPC更容易一些的方法,那么请考虑使用zeromq库(node.js绑定)。这个有点相关的答案也可能有用。
#1
3
I found a compute-cluster
module, which seems to be designed exactly for my goals. It spawns children processes, and the communication is made with IPC (no sockets wasted).
我发现了一个计算集群模块,它似乎完全符合我的目标。它产生子进程,并且使用IPC进行通信(没有浪费套接字)。
#2
1
The JavaScript language has no support for threads and node.js provides no interface to them either so you'll need to rely on a library to provide threading functionality. See the node-fibers and node-threads-a-go-go libraries for possible solutions.
JavaScript语言不支持线程和node.js也不提供任何接口,因此您需要依赖库来提供线程功能。有关可能的解决方案,请参阅node-fibers和node-threads-a-go-go库。
If you're looking for a way to make IPC a little easier in node.js then consider using the zeromq library (node.js bindings). This somewhat-related-answer might be useful as well.
如果您正在寻找一种在node.js中使IPC更容易一些的方法,那么请考虑使用zeromq库(node.js绑定)。这个有点相关的答案也可能有用。