Search This Blog

2016-02-17

Node Js Cluster

A cluster is a pool of similar workers running under a parent Node process. Workers are spawned using the fork() method of the child_processes module. This means workers can share server handles and use IPC (Inter-process communication) to communicate with the parent Node process.

The master process is in charge of initiating workers and controlling them. You can create an arbitrary number of workers in your master process. Moreover, remember that by default incoming connections are distributed in a round-robin approach among workers (except in Windows).

A cluster module contains several events. Two common events related to the moments of start and termination of workers are the online and the exit events. online is emitted when the worker is forked and sends the online message. exit is emitted when a worker process dies.

Example:

package.json
{
  "name": "democluster",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies":{
    "express":"*"
  }
}


index.js

var cluster = require('cluster');
if(cluster.isMaster) {
    var numWorkers = require('os').cpus().length;
    console.log('Master cluster setting up ' + numWorkers + ' workers...');
    for(var i = 0; i < numWorkers; i++) {
        cluster.fork();
    }
    cluster.on('fork', function(worker) {
        console.log('worker:' + worker.id + " is forked");
    });
    cluster.on('online', function(worker) {
        console.log('worker:' + worker.id + " is online");
    });
    cluster.on('listening', function(worker) {
        console.log('worker:' + worker.id + " is listening");
    });
    cluster.on('disconnect', function(worker) {
        console.log('worker:' + worker.id + " is disconnected");
    });
    cluster.on('exit', function(worker) {
        console.log('worker:' + worker.id + " is dead");
        console.log('Starting a new worker');
        cluster.fork();
    });

  
} else {
    var app = require('express')();
    app.all('/*', function(req, res) {res.send('process ' + process.pid + ' says hello!').end();})
    var server = app.listen(8000, function() {
        console.log('Process ' + process.pid + ' is listening to all incoming requests');
    });
}


OUTPUT IN CONSOLE:

Master cluster setting up 4 workers...
worker:1 is forked
worker:2 is forked
worker:3 is forked
worker:4 is forked
worker:1 is online
worker:4 is online
worker:2 is online
worker:3 is online
Process 8892 is listening to all incoming requests
worker:1 is listening
Process 16192 is listening to all incoming requests
worker:4 is listening
Process 9412 is listening to all incoming requests
Process 15596 is listening to all incoming requests
worker:3 is listening
worker:2 is listening

Reference: http://www.sitepoint.com/how-to-create-a-node-js-cluster-for-speeding-up-your-apps/

No comments: