Implement clustering in nodeJs
Posted By : Pulkit Chadha | 27-Sep-2017
Introduction:
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`);
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pulkit Chadha
Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.