// server.js
const cluster = require('cluster');
const cpuNums = require('os').cpus().length;
const http = require('http');
if (cluster.isMaster) {
console.info(`cpu: ${cpuNums}`);
for (var i = 0; i < cpuNums; i++) {
cluster.fork();
}
} else {
http.createServer(function(req, res) {
res.end(`response from worker ${process.pid}`);
}).listen(5000);
console.log(`Worker ${process.pid} started`);
}
建立測試腳本
for ((i = 1; i <= 8; i++)); do
curl <http://127.0.0.1:5000>
echo ""
done
輸出如下, 可以看到response來自不同的worker:
response from worker 7872
response from worker 7878
response from worker 7886
response from worker 7893
response from worker 7853
response from worker 7860
response from worker 7855
response from worker 7866