Implement clustering in nodeJs

Posted By : Pulkit Chadha | 27-Sep-2017

Introduction:

the cluster is one of the in-built modules of nodes i.e there is no need of installation for using this module.Using cluster module, we can start the multiple child processes that share the same port.we know that NodeJs is single threaded.so, to take the advantage of multi-core system,we can launch the cluster of node application to handle the server load.

Available Events and options:

1) Event: 'disconnect'
When any of the workers

are disconnected in the cluster module will call the 'disconnect' event.

 cluster.on('disconnect', (worker) => {
  console.log(`The worker'+ worker.id+' has disconnected`);
});
        

2) Event: 'exit'

When any of the workers in the cluster module die, it will call the 'exit' event.

cluster.on('exit', (worker, code, signal) => {
  console.log('worker'+worker.process.pid)+'died (%s). restarting...';
});
 
* worker : worked object.
* code: exit code, if it is exited normally.
* signal:  the name of the signal that caused the process to be killed.

3) cluster.isMaster:

If the process is master, it returns true else false.

4) cluster.isWorker:

If the process is the worker, it returns true else false.

5) worker.kill([signal='SIGTERM']):

This function will kill the worker process.

* signal: Name of the kill signal to send to the worker process.

Step 1: To achieve clustering in your application, add the code given below:

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker'+worker.process.pid+' died`);
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
        

About Author

Author Image
Pulkit Chadha

Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.

Request for Proposal

Name is required

Comment is required

Sending message..