Created
August 7, 2015 17:15
-
-
Save devotox/1a02e135d370299abf6b to your computer and use it in GitHub Desktop.
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
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