我正在开发一个应用程序的v2.0,对于这个新版本,我正在使用多线程来优化性能。我写了简单的代码,以了解节点之间如何平衡进程。这是代码:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
process.title = "xxxxx";
let count = {
1:0,
2:0,
3:0,
4:0
};
if (cluster.isMaster) {
console.clear()
console.log(`+ ${process.pid}`);
console.log(`|`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`|-- ${worker.process.pid} died`);
});
} else {
// Include Express
var express = require('express');
// Create a new Express application
var app = express();
// Add a basic route – index page
app.get('/', function (req, res) {
res.send("Process : " + process.pid + " Worker : " + cluster.worker.id);
count[cluster.worker.id] = count[cluster.worker.id] + 1
console.clear()
console.log(count)
});
// Bind to a port
app.listen(8080);
console.log(`|-- ${process.pid}`);
}
我原本希望在4名工作人员之间分配25%的负载。但是经过几次奔跑之后,我的炮兵脚本得到了
{ '1': 0, '2': 0, '3': 55000, '4': 0 }
战场上只有工人3,他们正在喝啤酒和纸牌。
我在Nodejs的负载平衡中做错了什么还是错过了某些东西?