我使用Cluster來解決單線程可靠性問題Cluster是內置庫之一,您可以將其配置爲啓動一個或(n)個工作者實例。在服務器的每個CPU核心的一個實例。其主要過程監控從工作進程的事件(我不知道過程是100%正確的說法),並能抓住終端,記錄它們,而且比重啓ŧ他工人。理想情況下,您還將希望擁有多個位於不同區域的Web服務器和負載平衡器,可以監控您的Web服務器,檢測它們何時超載或未響應,並採取適當的措施(例如啓動新實例並殺死死亡的服務器)
典型代碼使用集羣看起來是這樣的(基於例如集羣文檔中):
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
// restart this instance
cluster.fork();
});
} else {
// create an error handler for uncaught exceptions so we can log them
process.on('uncaughtException', function(err) {
var date = new Date();
var message = date.toString() + ":UNCAUGHT EXCEPTION\n" + err.stack + "\n";
console.log (message);
process.exit(1); // we will get restarted by the cluster process
});
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
}
http://nodejs.org/api/cluster.html – JohnnyHK
我不明白爲什麼這個問題應該被關閉。任何親密的選民都在關心解釋嗎? – 2012-12-29 04:24:00
+1 for @JohnnyHK - 集羣模塊爲您提供了一個小的「主」進程,它可以分派實際的Web應用程序處理的工作人員(通常等於CPU的數量)。然後,您會編寫一個小腳本來記錄和重新分配未處理錯誤的工作人員。下面是我寫的一個示例集羣包裝腳本(對不起,在CoffeeScript中,不是JS):https://gist.github.com/3656510 –