我尝试了节点集群而没有任何性能提升。可能是我错误地测量它。
使用 Node.js 7.4.0
server.js
const http = require('http');
const server = http.createServer((req, res) => {
for (let i = 0; i < 10000; i++) {
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end("Hello World!");
}).listen(4002);
我按照本教程创建了群集服务器http://rowanmanning.com/posts/node-cluster-and-express/
cluster.js
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(cluster.worker.id);
cluster.fork();
});
} else {
http.createServer((req, res) => {
for (let i = 0; i < 10000; i++) {
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end("Hello World!");
}).listen(4001);
}
当我这样做时,我可以看到4核上的主人和工人的pids
$ps axl | grep node
0 0 8799 8789 20 0 682196 28056 ep_pol Sl+ pts/1 0:00 node index.js
0 0 8805 8799 20 0 682196 27708 ep_pol Sl+ pts/1 0:00 /usr/bin/nodejs /home/ubuntu/index.js
0 0 8811 8799 20 0 682196 27608 ep_pol Sl+ pts/1 0:00 /usr/bin/nodejs /home/ubuntu/index.js
0 0 8812 8799 20 0 682196 27756 ep_pol Sl+ pts/1 0:00 /usr/bin/nodejs /home/ubuntu/index.js
0 0 8818 8799 20 0 682196 27604 ep_pol Sl+ pts/1 0:00 /usr/bin/nodejs /home/ubuntu/index.js
由于 Rowan 声称性能提升4倍,因此我几乎没有从群集中获得任何性能。
我的围攻结果是 t2.xlarge AWS实例(4核心)ubuntu机器。
server.js - $siege -c100 -t1M http://xx.xx.xx.xx:4002/
Transactions: 13545 hits
Availability: 100.00 %
Elapsed time: 59.39 secs
Data transferred: 0.16 MB
Response time: 0.19 secs
Transaction rate: 228.07 trans/sec
Throughput: 0.00 MB/sec
Concurrency: 42.30
Successful transactions: 13545
Failed transactions: 0
Longest transaction: 11.61
Shortest transaction: 0.02
现在为cluster.js
cluster.js - $siege -c100 -t1M http://xx.xx.xx.xx:4001/
Transactions: 13223 hits
Availability: 100.00 %
Elapsed time: 59.96 secs
Data transferred: 0.15 MB
Response time: 0.16 secs
Transaction rate: 220.53 trans/sec
Throughput: 0.00 MB/sec
Concurrency: 35.95
Successful transactions: 13223
Failed transactions: 0
Longest transaction: 11.56
Shortest transaction: 0.02
令人惊讶的是,与server.js相比,cluster.js表现不佳。
我做错了吗?它是node.js版本的变化吗?或者这些说法是假的吗?
https://keyholesoftware.com/2015/01/26/improve-node-js-performance-by-turning-it-into-a-clusterfork/
https://www.sitepoint.com/how-to-create-a-node-js-cluster-for-speeding-up-your-apps/
非常感谢任何帮助。
答案 0 :(得分:1)
所以这类似于:
NodeJS clustering sending all the request to one worker (Windows)
和
clustering in node.js is not working. Only one worker is always responding
尝试类似:
http.createServer(function(req, res) {
console.log('worker:' + cluster.worker.id + " going to send response ");
//(Heavy I/O operation...followed by res.send(result))
}).listen(8000);