Last active
October 31, 2015 12:09
-
-
Save vermaslal/b28dbd32579f82601dcf to your computer and use it in GitHub Desktop.
Improve node.js app performance using Clustering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cluster = require('cluster'); | |
var numCPUs = require('os').cpus().length; | |
var express = require("express"); | |
var app = express(); | |
if (cluster.isMaster) { | |
// Fork workers. | |
for (var i = 0; i < numCPUs; i++) { | |
cluster.fork(); | |
} | |
Object.keys(cluster.workers).forEach(function (id) { | |
console.log("I am running with ID : " + cluster.workers[id].process.pid); | |
}); | |
cluster.on('exit', function (worker, code, signal) { | |
console.log('worker ' + worker.process.pid + ' died'); | |
}); | |
} else { | |
app.get('/', function (req, res) { | |
res.end("Hello world from " + process.pid); | |
}); | |
app.listen(3000, function () { | |
console.log(process.pid, " is running at PORT 3000"); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment