gpt4 book ai didi

node.js - Nodejs 集群未列出

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

这是从nodejs api复制的:

我想做的是在master中做后台工作,并在worker中接受http请求。

如果我注释掉后台作业部分,效果很好。

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
const sleep = require('sleep');

if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);

// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}

cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});


// background jobs start
while(true) {
console.log(123)
sleep.sleep(1) // do_background_jobs()
}
// background jobs end


} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);

console.log(`Worker ${process.pid} started`);
}

这是日志:

Master 45476 is running
Worker 45479 started
Worker 45483 started
Worker 45482 started
Worker 45478 started

但是netstat显示8000已关闭。当然 curl 失败了。

最佳答案

您的 while 循环阻塞了“event loop ”,因此主进程中不会发生任何事情。您应该将 while 循环转换为此代码以防止阻塞 IO。

setInterval(() => {
console.log("123")
}, 1000)

关于node.js - Nodejs 集群未列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062949/

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