2017-05-18 30 views
0

許多人說集羣模塊使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。

+0

絕對迴應是不可能的。 它取決於你的代碼,請附上你的代碼到這個問題 –

+0

該腳本是在問題的github回購。 –

回答

0

我嘗試設置的調度策略對集羣腳本SCHED_NONE

cluster.schedulingPolicy = cluster.SCHED_NONE 

現在集羣腳本不斷優於非羣集腳本。 yeeah

+0

如果您使用的是Windows,似乎有一些問題與默認值https://nodejs.org/api/cluster.html#cluster_cluster_schedulingpolicy –