Skip to content

Instantly share code, notes, and snippets.

@devotox
Created August 7, 2015 17:16
Show Gist options
  • Save devotox/0eeef7c5e377f31a5c43 to your computer and use it in GitHub Desktop.
Save devotox/0eeef7c5e377f31a5c43 to your computer and use it in GitHub Desktop.
(function () {
'use strict';
var cluster = require('cluster'),
http = require('http'),
os = require('os'),
ClusterServer,
workers = {};
/*
* ClusterServer object
*
* We start multi-threaded server instances by passing the server object
* to ClusterServer.start(server, port).
*
* Servers are automatically started with a number of threads equivalent
* to the number of CPUs reported by the os module.
*/
ClusterServer = {
name: 'API',
autoRestart: true,
cpus: os.cpus().length,
start: function (startWorker) {
var me = this, i;
if (cluster.isMaster) { // fork worker threads
for (i = 0; i < me.cpus; i += 1) {
console.log(me.name + ': starting worker thread #' + i);
var worker = cluster.fork();
workers[worker.pid] = worker;
}
console.log("Number of CPU's:", me.cpus, "\n");
cluster.on('death', function (worker) {
// Log deaths!
console.log(me.name + ': worker ' + worker.pid + ' died.');
// If autoRestart is true, spin up another to replace it
if (me.autoRestart) {
console.log(me.name + ': Restarting worker thread...');
cluster.fork();
}
});
} else {
// Worker threads run the server
return startWorker();
}
}
}
ClusterServer.start(function() {
require(process.cwd() + '/api/app.js').listen(process.env.NODE_PORT || 3000);
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment