在快速服务器中产生子进程 [英] Spawning child processes in an express server

查看:107
本文介绍了在快速服务器中产生子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的快速服务器中,我需要运行一些函数作为子进程,否则它们将占用服务器而其他人将无法访问它。他们已经在使用异步模块,但它们仍然会占用服务器,除非它们作为子进程运行。

In my express server there are some functions which I need to run as child processes because otherwise they'll tie up the server and other people won't be able to access it. They're already using the async module but they still tie up the server unless they're run as child processes.

一个问题是将req和res参数传递给它们。

One problem is passing the req and res parameters to them.

如何做到这一点?

推荐答案

使用 child_process.fork ,您可以向子进程发送消息。

Using child_process.fork, you can send messages to child processes.

编辑:我错误地建议传递 req res 作为子进程的消息参数。这是不可能的,因为进出子进程的所有消息都转换为JSON。相反,您可以在服务器中保留某种队列。以下仅作为示例,您可能需要更强大的功能:

I incorrectly advised to pass req and res as message parameters to the child process. This is not possible, as all messages to and from child processes are converted to JSON. Instead, you could keep some kind of queue in your server. The below is only meant as an example, you may want something more robust:

child.js:

process.on('message', function(message) {
    // Process data

    process.send({id: message.id, data: 'some result'});
});

server.js:

server.js:

var child_process = require('child_process');
var child = child_process.fork(__dirname + '/child.js');
var taskId = 0;
var tasks = {};

function addTask(data, callback) {
    var id = taskId++;

    child.send({id: id, data: data});

    tasks[id] = callback;
};

child.on('message', function(message) {
    // Look up the callback bound to this id and invoke it with the result
    tasks[message.id](message.data);
});

app.post('/foo', function(req, res) {
    addTask('some data', function(result) {
        res.send(result);
    });
});

它涉及更多,但它应该有效。你可能会很快从这样的系统中发展出来,并且可以通过适当的队列来提供更好的服务。

It's a bit more involved, but it should work. You may quickly grow out of such a system, and may be better served by a proper queue.

这篇关于在快速服务器中产生子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆