gpt4 book ai didi

node.js - 当将 http.createServer 与集群一起使用时,为什么为 http.createServer 提供的回调被多次调用?

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:18 25 4
gpt4 key购买 nike

我试图了解集群的工作人员如何处理 http 请求。我从 http://nodejs.org/api/cluster.html 的代码开始并在其周围添加了一些日志记录。

我将以下代码放入 server.js 中并使用以下命令执行该文件:NODE_DEBUG=集群 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);
}

然后我访问了 localhost:8000 一次,你瞧,“hello world”就是我预期的响应。我没想到的是一些日志语句被打印了两次:

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

相反,我的函数由同一个工作人员执行两次。有人可以解释一下吗?

最佳答案

您检查过req.url吗?我打赌这两个请求之一是针对 /favicon.ico 的。

关于node.js - 当将 http.createServer 与集群一起使用时,为什么为 http.createServer 提供的回调被多次调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26500005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com