Created
November 5, 2011 11:30
-
-
Save netroy/1341411 to your computer and use it in GitHub Desktop.
Using cluster to scale existing Express/Connect apps
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'), | |
app = require('./app'); | |
var workers = {}, | |
count = require('os').cpus().length; | |
function spawn(){ | |
var worker = cluster.fork(); | |
workers[worker.pid] = worker; | |
return worker; | |
} | |
if (cluster.isMaster) { | |
for (var i = 0; i < count; i++) { | |
spawn(); | |
} | |
cluster.on('death', function(worker) { | |
console.log('worker ' + worker.pid + ' died. spawning a new process...'); | |
delete workers[worker.pid]; | |
spawn(); | |
}); | |
} else { | |
app.listen(process.env.app_port || 5000); | |
} |
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 express = require('express'), | |
app = module.exports = express.createServer(); | |
app.configure(function(){ | |
app.use(app.router); | |
}); | |
app.get('/', function(req, resp){ | |
resp.writeHead(200, "Content-type: text/json"); | |
resp.write("Hello Node"); | |
resp.end(); | |
}); | |
if (!module.parent) { | |
app.listen(process.env.app_port || 5000); | |
} |
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 connect = require('connect'), | |
app = module.exports = connect.createServer(); | |
app.use(connect.router(function(router){ | |
router.get("/", function(req, resp){ | |
resp.writeHead(200, "Content-type: text/json"); | |
resp.write("Hello Node"); | |
resp.end(); | |
}); | |
})); | |
if (!module.parent) { | |
app.listen(process.env.app_port || 5000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment