私はクラスターを使用して、シングル スレッドの信頼性の問題を回避しています。クラスターは組み込みライブラリの 1 つであり、1 つまたは (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);
}