Skip to content

Instantly share code, notes, and snippets.

@darimpulso
Last active April 16, 2018 20:18
Show Gist options
  • Save darimpulso/9365755 to your computer and use it in GitHub Desktop.
Save darimpulso/9365755 to your computer and use it in GitHub Desktop.
Node Cluster with redis
var cluster = require("cluster")
, redis = require("redis") // Needs redis server
, os = require('os');
var cpus = os.cpus();
var workers = cpus.length || 2;
if(cluster.isMaster) {
for (var i = 0;i < workers; i++) {
var worker = cluster.fork().process;
console.log('worker %s started.', worker.pid);
}
var sub = redis.createClient();
sub.psubscribe('msg:*');
sub.on('pmessage', function(pool, channel, msg){
// Solution to update all instances
messageHandler(msg);
// Solution to update on instance
var workerKeys = _.keys(cluster.workers);
var selectedWorker = cluster.workers[workerKeys[0]];
if(sworker)
selectedWorker.send({...});
})
function eachWorker(callback) {
for (var id in cluster.workers) {
callback(cluster.workers[id]);
}
}
function messageHandler(msg) {
eachWorker(function(worker){
worker.send(msg);
})
}
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message', messageHandler);
});
cluster.on("exit", function(worker, code){
console.log("worker no "+worker.id+' died');
cluster.fork();
})
} else {
// Do something with the workers
}
process.on('uncaughtException', function (err) {
console.error(err);
if(err.code !== "ECONNRESET")
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment