Clusterモジュールを使うと簡単に
クラスタを実装できます。
導入すると何が良いの? → マルチコア環境で処理能力があがります。
というわけで実装します。どういう仕組みかは「
Cluster」を参照してください。
まずは実験環境を導入します。Nodeがインストールされている環境で以下のようにしてください。
$ mkdir cluster-test
$ cd cluster-test
$ npm install cluster
実験用のserver.jsを作成します。
$ emacs -nw server.js
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (var i=0; i < numCPUs; i++) {
// if master, then fork
var worker = cluster.fork();
}
cluster.on('listening', function(worker) {
console.log('worker is listening. pid: ' + worker.process.pid);
});
cluster.on('exit', function(worker) {
console.log('worker is killed. pid: ' + worker.process.pid);
});
} else {
http.Server(function(req, res) {
res.writeHead(200);
res.end('Hello');
}).listen(3000);
console.log('server start: http://localhost:3000');
}
// if not this event, processes are alive
process.on('SIGINT', function() {
if (cluster.isMaster) {
console.log('master stopped. pid: ' + process.pid);
} else {
console.log('worker stopped. pid: ' + process.pid);
}
process.exit(0);
});
これで
$ node server.js
とするとCPUの分だけ子プロセスが起動します。
Ctrl-cすると 'SIGINT' のイベントでプロセスが終了しますし、
kill すると 'exit' イベントでプロセスが終了します。
ソース:
Cluster
node.js v0.8.1のClusterモジュールを試す
CPUを最大限活かそう。Nodeでclusterを使ってみる