Last active
December 26, 2015 13:29
-
-
Save jamlfy/7159005 to your computer and use it in GitHub Desktop.
To balance clustered nodejs actually generates greater stability
This file contains hidden or 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
const cluster = require('cluster'); | |
const http = require('http'); | |
const httpProxy = require('http-proxy'); | |
const _ = require('underscore'); | |
var numCPUs = 10; | |
var isPort = 8080; | |
function estimatePi() { | |
var n = 10000000, inside = 0, i, x, y; | |
for ( i = 0; i < n; i++ ) { | |
x = Math.random(); | |
y = Math.random(); | |
if ( Math.sqrt(x * x + y * y) <= 1 ) | |
inside++; | |
} | |
return 4 * inside / n; | |
} | |
if (cluster.isMaster) { | |
var addresses = []; | |
var is = 0; | |
// Fork workers. | |
for (var i = 0; i < numCPUs; i++) cluster.fork(); | |
httpProxy.createServer(function (req, res, proxy) { | |
var add = _.filter( addresses, function (server){ | |
return _.isNumber( server.port ) && !_.isNaN( server.port ); | |
}); | |
is = is >= (add.length * 100) ? add.length - 1 : i++; | |
var ReServer = ( is + 1 ) % add.length; | |
proxy.proxyRequest(req, res, add[ ReServer ] ); | |
}).listen( isPort ); | |
cluster | |
.on('online', function (worker){ | |
addresses.push( { host : 'localhost', port : worker.process.pid } ); | |
}) | |
.on('exit', function (worker, code, signal) { | |
addresses = _.without(addresses, { host : 'localhost', port : worker.process.pid }); | |
console.log('worker ' + worker.process.pid + ' died'); | |
cluster.fork(); | |
}); | |
} else { | |
if(isPort === process.pid ) | |
return process.exit(); | |
// Workers can share any TCP connection | |
// In this case its a HTTP server | |
http.createServer(function (req, res) { | |
res.writeHead(200, { 'Content-Type' : 'text/html' }); | |
res.end('Pi: ' + estimatePi() ); | |
}).listen( process.pid ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment