我试图了解群集工作者如何提供http请求。我开始使用http://nodejs.org/api/cluster.html处的代码并添加了一些日志记录。
我将以下代码放在server.js中并执行以下文件: NODE_DEBUG =群集节点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);
}
然后我去了localhost:8000一次,然后看看,#34;你好世界&#34;是我预期的回应。我没想到的是一些日志语句被打印两次:
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
具体来说,我预计对于我的服务器的一个请求,以下行只会打印一次:
someVar.b current value: X. someVar.b will be incremented
Request being processed by worker: XXX
response ended by worker: XXX
相反,我的功能被同一个工作人员执行两次。有人可以对此有所了解吗?
答案 0 :(得分:0)
您检查过req.url
了吗?我打赌这两个请求之一是/favicon.ico
。