许多人说集群模块使node.js应用程序比普通应用程序更快。但是我在这里遇到的是某种混乱。我创建了两个脚本,第一个是不使用集群模块的常规http服务器。第二个脚本是使用集群模块的http服务器。为什么非集群应用在nodejs中胜过集群应用?
我正在使用Apache基准向这些服务器发送高请求。结果如下:
Attempt#1:
non-cluster: 15,418 req/sec
cluster: 10,333 req/sec
Attempt#2:
non-cluster: 12,563 req/sec
cluster: 9,874 req/sec
非集群脚本如何超过集群脚本?
这里是github repo的脚本。
非群集脚本:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World!');
});
server.listen(process.env.SERVER_PORT,() => {
console.log('Server started on port ' + process.env.SERVER_PORT);
});
集群脚本:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
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`);
});
} 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!');
}).listen(process.env.SERVER_PORT);
console.log(`Worker ${process.pid} started`);
}
我的节点版本是7.10在Ubuntu 16.04。
绝对回应是不可能的。 它取决于你的代码,请附上你的代码到这个问题 –
该脚本是在问题的github回购。 –