-
-
Save jpoehls/2232358 to your computer and use it in GitHub Desktop.
var cluster = require('cluster'); | |
if (cluster.isWorker) { | |
console.log('Worker ' + process.pid + ' has started.'); | |
// Send message to master process. | |
process.send({msgFromWorker: 'This is from worker ' + process.pid + '.'}) | |
// Receive messages from the master process. | |
process.on('message', function(msg) { | |
console.log('Worker ' + process.pid + ' received message from master.', msg); | |
}); | |
} | |
if (cluster.isMaster) { | |
console.log('Master ' + process.pid + ' has started.'); | |
// Fork workers. | |
for (var i = 0; i < 2; i++) { | |
var worker = cluster.fork(); | |
// Receive messages from this worker and handle them in the master process. | |
worker.on('message', function(msg) { | |
console.log('Master ' + process.pid + ' received message from worker ' + this.pid + '.', msg); | |
}); | |
// Send a message from the master process to the worker. | |
worker.send({msgFromMaster: 'This is from master ' + process.pid + ' to worker ' + worker.pid + '.'}); | |
} | |
// Be notified when worker processes die. | |
cluster.on('death', function(worker) { | |
console.log('Worker ' + worker.pid + ' died.'); | |
}); | |
} |
Great example. Thanks a lot!
can use os.cpus().length
to get number of running workers if you do not know the exact number as indicated in the for loop.
(Be sure to var os = require('os')
when using)
I have a Map()
object which I use to store on fly values for my app so how I can share this object between all workers ?
I am using .set()
and .get()
methods of this object also.
I've created a module to make communicating between the master and worker easier: https://github.com/Rob--/cluster-messages
Great! thanks 👍
Why would workers need to communicate between other workers? Shouldn't the database be the single point of truth that each worker gets any persisted data from?
@BriantAnthony thanks for the reminder (really)!
nice example, thanks.
Why would workers need to communicate between other workers? Shouldn't the database be the single point of truth that each worker gets any persisted data from?
For many reasons. For example in a big project you need some parallel computing for improving performance, the database wouldn't be a solution because it would end up being a bottleneck of performance. Take a look on this DigitalOcean case study: https://medium.com/better-programming/from-15-000-database-connections-to-under-100-dfd34062da4c
Additionally, persistent data is not always the case.
Just to NOTE: workers keep on sending some internal nodejs related data to the master, so keep a check on msg
key
Great stuff.
Good example.
Need to replace
this.pid
forthis.process.pid
on newer Node versions.Same for
worker.pid