2011-10-12 23:19:32 +02:00
|
|
|
## Cluster
|
|
|
|
|
|
|
|
A single instance of Node runs in a single thread. To take advantage of
|
|
|
|
multi-core systems the user will sometimes want to launch a cluster of Node
|
|
|
|
processes to handle the load.
|
|
|
|
|
2011-10-26 22:41:31 +02:00
|
|
|
The cluster module allows you to easily create a network of processes all
|
|
|
|
which share server ports.
|
2011-10-12 23:19:32 +02:00
|
|
|
|
2011-10-27 01:21:08 +02:00
|
|
|
var cluster = require('cluster');
|
|
|
|
var http = require('http');
|
2011-11-04 23:11:19 +01:00
|
|
|
var numCPUs = require('os').cpus().length;
|
2011-10-27 01:21:08 +02:00
|
|
|
|
|
|
|
if (cluster.isMaster) {
|
2011-11-04 23:11:19 +01:00
|
|
|
// Fork workers.
|
|
|
|
for (var i = 0; i < numCPUs; i++) {
|
|
|
|
cluster.fork();
|
|
|
|
}
|
|
|
|
|
|
|
|
cluster.on('death', function(worker) {
|
|
|
|
console.log('worker ' + worker.pid + ' died');
|
|
|
|
});
|
2011-10-27 01:21:08 +02:00
|
|
|
} else {
|
|
|
|
// Worker processes have a http server.
|
|
|
|
http.Server(function(req, res) {
|
|
|
|
res.writeHead(200);
|
|
|
|
res.end("hello world\n");
|
|
|
|
}).listen(8000);
|
|
|
|
}
|
|
|
|
|
|
|
|
Running node will now share port 8000 between the workers:
|
|
|
|
|
|
|
|
% node server.js
|
2011-10-12 23:19:32 +02:00
|
|
|
Worker 2438 online
|
|
|
|
Worker 2437 online
|
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
### cluster.fork()
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
Spawn a new worker process. This can only be called from the master process.
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
### cluster.isMaster
|
|
|
|
### cluster.isWorker
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
Boolean flags to determine if the current process is a master or a worker
|
|
|
|
process in a cluster. A process `isMaster` if `process.env.NODE_WORKER_ID`
|
|
|
|
is undefined.
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
### Event: 'death'
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
When any of the workers die the cluster module will emit the 'death' event.
|
|
|
|
This can be used to restart the worker by calling `fork()` again.
|
2011-10-27 01:21:08 +02:00
|
|
|
|
2011-11-04 23:11:19 +01:00
|
|
|
cluster.on('death', function(worker) {
|
|
|
|
console.log('worker ' + worker.pid + ' died. restart...');
|
|
|
|
cluster.fork();
|
|
|
|
});
|
|
|
|
|
|
|
|
Different techniques can be used to restart the worker depending on the
|
|
|
|
application.
|