简体   繁体   中英

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.

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.

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. Instead, when I try to issue multiple requests using curl, all requests are processed sequentially by one single worker; no other workers are ever invoked even though they've been forked.

Could it be that I'm using Express incorrectly? 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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