Saturday, November 25, 2017

How to create a nodejs cluster

Each Nodejs process runs in a single thread by default, but nodejs gives one more important advantage to run your web application in computer's multi-core systems.

The cluster module is used to create child processes that each runs on their own single thread, to handle the load.

Demo

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('online', function(worker) {
        console.log('Worker ' + worker.process.pid + ' is online.');
    });

    cluster.on('exit', function(worker, code, signal) {
        console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
        console.log('Starting a new worker');
        cluster.fork();
    });
} else {
            //here you can add your exprejs, nodejs modules, and configuration
            require("./app.js"); //you can make a separate file or you can put your main file's code here
           //If you don't want to make separate file the you can run put your code here
           //http.createServer(function(req, res) {
                //...
                //...
                //...
           //}).listen(3000);
}

app.js

var express  = require('express');
var app      = express();
var mongoose = require('mongoose'); // mongoose for mongodb
var port   = process.env.PORT || 3000;  // set the port

var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var expressSession = require('express-session');
var cookieParser = require('cookie-parser'); // the session is stored in a cookie, so we use this to parse it
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

/*
 * MongoDB connection
 */
var mongoURI = "mongodb://localhost:27017/myDatabaseName";
var mongoDB = mongoose.connect(mongoURI).connection;

mongoDB.on("error", function (err) {
    logger.log("error", "connection does not established: " + mongoURI);
});

mongoDB.once("open", function () {
    logger.log("info", "connection established: " + mongoURI);
});

/*
* must use cookieParser before expressSession
*/
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere',resave: true,saveUninitialized: true}));

app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());

/*
*routes
*/
require('./app/routes.js')(app);

/*
*application listen
*/
app.listen(port);
console.log("App listening on port " + port);

From the above demo, your application will run and you can get the advantage of using full CPU.

If your server has four core processor then your application will use these all processor so that your application performance will improve and request connections will increase.

here, we have put cluster.fork(); in exit method to start working again if one of all worker stops/die due to some issue.

No comments:

Post a Comment