0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-29 15:06:33 +01:00
nodejs/doc/api/cluster.markdown

60 lines
1.6 KiB
Markdown
Raw Normal View History

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.
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
var cluster = require('cluster');
var http = require('http');
2011-11-04 23:11:19 +01:00
var numCPUs = require('os').cpus().length;
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');
});
} 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-11-04 23:11:19 +01:00
Spawn a new worker process. This can only be called from the master process.
2011-11-04 23:11:19 +01:00
### cluster.isMaster
### cluster.isWorker
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-11-04 23:11:19 +01:00
### Event: 'death'
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-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.