问题描述:

I was trying to understand how http requests are served by workers of a cluster. I started with the code at http://nodejs.org/api/cluster.html and added some logging around it.

I put the following code in server.js and executed the file with:

NODE_DEBUG=cluster node server.js

var cluster = require('cluster');

var http = require('http');

var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {

console.log('number of CPUs: ' + numCPUs);

// Fork workers.

for (var i = 0; i < numCPUs; i++) {

console.log('forking worker ' + i);

cluster.fork();

}

cluster.on('exit', function(worker, code, signal) {

console.log('worker ' + worker.process.pid + ' died');

});

} else {

console.log('worker spawned: ' + cluster.worker.process.pid);

var someVar = {'b': 1};

// Workers can share any TCP connection

// In this case its a HTTP server

http.createServer(function(req, res) {

console.log('someVar.b current value: ' + someVar.b + ". someVar.b will be incremented");

someVar.b = someVar.b + 1;

console.log('Request being processed by worker: ' + cluster.worker.process.pid);

res.writeHead(200);

res.end("hello world\n");

console.log('response ended by worker: ' + cluster.worker.process.pid);

}).listen(8000);

}

I then went to localhost:8000 once, and lo and behold, "hello world" was the response as I expected. What I didn't expect is some log statements being printed twice:

number of CPUs: 2

forking worker 0

forking worker 1

535,Master Worker 536 online

535,Master Worker 537 online

worker spawned: 536

worker spawned: 537

someVar.b current value: 1. someVar.b will be incremented

Request being processed by worker: 536

response ended by worker: 536

someVar.b current value: 2. someVar.b will be incremented

Request being processed by worker: 536

response ended by worker: 536

Specifically, I expected that for one request to my server, the following lines would only be printed once:

someVar.b current value: X. someVar.b will be incremented

Request being processed by worker: XXX

response ended by worker: XXX

Instead my functions are getting executed twice by the same worker. Could someone please shed some light on this?

网友答案:

Did you check req.url? I bet one of the two requests is for /favicon.ico.

相关阅读:
Top