Cluster & Toobusy - an awesomely scalable node setup
// Include libraries | |
var express = require('express'); | |
var cluster = require('cluster'); | |
var toobusy = require('toobusy'); | |
if (cluster.isMaster) { | |
var cpus = require("os").cpus(); | |
console.log("CPU Info:"); | |
console.log(cpus); | |
for (var i = 0; i < cpus.length; i++) { | |
cluster.fork(); | |
} | |
console.log("Running master"); | |
} else { | |
// Create a new Express application | |
var app = express(); | |
app.use(function(req, res, next) { | |
if (toobusy()) res.send(503, "Server melting, sorry :)"); | |
else next(); | |
}); | |
// Add a basic route – index page | |
app.get('/', function (req, res) { | |
res.send('Hello World from the world of worker ' + cluster.worker.id + '!'); | |
console.log("Serving from worker " + cluster.worker.id); | |
}); | |
// Bind to a port | |
app.listen(3000); | |
console.log("Running worker " + cluster.worker.id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment