简体   繁体   English

Node.js Cluster + Express始终调用同一工作程序

[英]Node.js Cluster + Express always invoke the same worker

I'm trying to use the cluster module to handle multiple http requests concurrently with Express. 我正在尝试使用群集模块与Express同时处理多个http请求。

With the code below I'm able to spawn multiple workers and have all of them listen on the same port. 使用下面的代码,我可以产生多个工作程序,并让他们全部在同一端口上侦听。 The large for loop is there to simulate heavy load on the web server. 大的for循环可用来模拟Web服务器上的繁重负载。

What I'd like to see is that if a worker is busy processing one http request when a second request comes in, a different worker will get invoked and handle that second request. 我想看到的是,如果一个工作线程在第二个请求出现时正忙于处理一个http请求,则将调用另一个工作线程并处理该第二个请求。 Instead, when I try to issue multiple requests using curl, all requests are processed sequentially by one single worker; 相反,当我尝试使用curl发出多个请求时,所有请求都由一个工作人员按顺序处理; no other workers are ever invoked even though they've been forked. 即使已经分叉,也没有其他工人被调用过。

Could it be that I'm using Express incorrectly? 可能是我使用Express的方式不正确吗? Thanks in advance! 提前致谢!

var cluster = require('cluster');
if (cluster.isMaster) {
    var cpuCount = require('os').cpus().length;
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }
}

else {
    var http = require('http'),
    app = require('express')();

    http.createServer(app).listen(31415, function () {
        console.log(process.pid + " listening on 31415");
    });

    app.get('/', function (req, res) {
        var t= 0;
        for(var i=0; i < 100000000; i++){
            t++;
        }
        res.send('done');
    });
}

Try not to use built-in module ? 尝试不使用内置模块?

master.js master.js

var cp = require('child_process');
var net = require('net');
// create tcp server listen to a port
var tcp = net.createServer();
tcp.listen(8000, function(){
    // detect cpu number, and fork child process
    for (var i=0;i< require('os').cpus().length; i++) {
        var worker = cp.fork('child.js');
        worker.send(i, tcp._handle);
    }
    tcp.close();
});

child.js child.js

var express = require('express');
var app = express();
process.on('message', function(id, handle){

    app.get('/',function(){
        console.log(process.pid+' is listening ...');
    });
    app.listen(handle, function(){
        console.log(process.pid + 'started');
    });
});

this works fine with express 3.x 这适用于Express 3.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM