Created
June 27, 2013 04:09
-
-
Save jmervine/5873883 to your computer and use it in GitHub Desktop.
Clustering in Node.js
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
/** | |
* Libraries | |
**/ | |
var cluster = require('cluster'); | |
var datefmt = require('dateformat'); | |
/** | |
* Setup | |
**/ | |
var workers = parseInt(process.env.CLUSTER_WORKERS, 8); | |
cluster.setupMaster({ | |
exec : "app.js", | |
}); | |
/** | |
* Utilities | |
**/ | |
function say(message) { | |
console.log("[SERVER] " + message); | |
}; | |
/** | |
* Startup Messaging | |
**/ | |
say("Master starting:"); | |
say("time => " + datefmt(new Date(), "ddd, dd mmm yyyy hh:MM:ss Z")); | |
say("pid => " + process.pid); | |
say("environment => " + process.env.NODE_ENV); | |
/** | |
* Fork Workers | |
**/ | |
say("Workers starting:"); | |
for (var i = 0; i < workers; i++) { | |
cluster.fork(); | |
} | |
/** | |
* Worker Event Handlers | |
**/ | |
cluster.on('exit', function(worker, code, signal) { | |
say('worker => with pid: ' + worker.process.pid + ', died. Restarting...'); | |
cluster.fork(); | |
}); | |
cluster.on('online', function(worker) { | |
say('worker => start with pid: ' + worker.process.pid + '.'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment