Skip to content

Instantly share code, notes, and snippets.

@laurisvan
Created July 4, 2013 19:02
Show Gist options
  • Save laurisvan/5929663 to your computer and use it in GitHub Desktop.
Save laurisvan/5929663 to your computer and use it in GitHub Desktop.
A simple node.js/express example on how to 'misuse' cluster to actually create several process forks, and set their own port for each.
var express = require('express'),
cluster = require('cluster'),
http = require('http'),
numCPUs = require('os').cpus().length,
basePort = 1100;
var app = express();
app.use(express.cookieParser());
app.use(express.logger('short'));
app.use(express.session({
secret: 'keyboard cat',
key: 'backendSession',
// Disabled for better readability
//cookie: { secure: true },
store: new express.session.MemoryStore
}));
app.get('/api/*', function(req, res) {
var session = req.session,
body = 'Hello World from ' + app.locals.port;
// Store something to the session
// Note: In a real-world example, don't set a cookie when you dont't want
// to disable Nginx caching mechanisms.
session.stickyPort = app.locals.port;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
// Since we don't share the same port, pass it as an env. variable
cluster.fork({ 'SLAVE_PORT': basePort + i});
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// Fetch the port fron ENV
var port = process.env['SLAVE_PORT'];
// Workers can share any TCP connection
// In this case its a HTTP server
app.listen(port);
app.locals.port = port;
console.log('Slave listening at port', port);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment