Last active
July 5, 2018 02:57
-
-
Save WaleedAshraf/7842f728b06b0ed794ec5bb836e82c85 to your computer and use it in GitHub Desktop.
Switching from cluster module to PM2 & RabbitMQ
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
var cluster = require('cluster'); | |
const numCPUs = require('os').cpus().length; | |
module.exports.create = function (options, callback) { | |
if (cluster.isMaster) { | |
// fork child process for notif/sms/email worker | |
global.smsWorker = require('child_process').fork('./smsWorker'); | |
global.emailWorker = require('child_process').fork('./emailWorker'); | |
global.notifiWorker = require('child_process').fork('./notifWorker'); | |
// fork application workers | |
for (var i = 0; i < numCPUs; i++) { | |
var worker = cluster.fork().process; | |
console.log('worker started. process id %s', worker.pid); | |
} | |
// if application worker gets disconnected, start new one. | |
cluster.on('disconnect', function (worker) { | |
console.error('Worker disconnect: ' + worker.id); | |
var newWorker = cluster.fork().process; | |
console.log('Worker started. Process id %s', newWorker.pid); | |
}); | |
cluster.on('online', function (worker) { | |
console.log('New worker is online. worker: ' + worker.id); | |
// master receive messages and then forward it to worker based on type. | |
worker.on('message', function (message) { | |
switch (message.type) { | |
case 'sms': | |
global.smsWorker.send(message); | |
break; | |
// each of these worker is listning to process.on('message') | |
// and then perform relevant tasks. | |
case 'email': | |
global.emailWorker.send(message); | |
break; | |
case 'notif': | |
global.notifWorker.send(message); | |
break; | |
} | |
}); | |
}); | |
} else { | |
global.smsWorker = { | |
send: function (message) { | |
message.type = 'sms'; | |
process.send(message); // send message to master | |
console.log('sms Message sent from worker.'); | |
} | |
}; | |
global.emailWorker = { | |
send: function (message) { | |
message.type = 'email'; | |
process.send(message); // send message to master | |
console.log('email Message sent from worker.'); | |
} | |
}; | |
global.notifWorker = { | |
send: function (message) { | |
message.type = 'notif'; | |
process.send(message); // send message to master | |
console.log('notification Message sent from worker.'); | |
} | |
}; | |
callback(cluster); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment