You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.6 KiB

## 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.
The cluster module allows you to easily create a network of processes all
which share server ports.
var cluster = require('cluster');
var http = require('http');
13 years ago
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
13 years ago
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
} 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
Worker 2438 online
Worker 2437 online
13 years ago
### cluster.fork()
13 years ago
Spawn a new worker process. This can only be called from the master process.
13 years ago
### cluster.isMaster
### cluster.isWorker
13 years ago
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.
13 years ago
### Event: 'death'
13 years ago
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.
13 years ago
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.