S
S
SalimILE2015-11-25 09:36:36
Node.js
SalimILE, 2015-11-25 09:36:36

How to implement clustering in nodejs?

Hello, please tell me what is the difference between the two codes
1 =>

if (cluster.isMaster) {
         var count = 0
         while(CPUs.length > count++) {
            log.debug("Worker booted with ID: [" + cluster.fork().process.pid + "]")
         } 

         cluster.on('exit', function (worker) {
            log.error("Worker with ID: [" + worker.process.pid + "] died")
            setTimeout(function () { cluster.fork() }, 1000)
         })
      } else {
        
          // HERE
         require("/server")
      }

2=>
if (cluster.isMaster) {
         var count = 0
         while(CPUs.length > count++) {
            log.debug("Worker booted with ID: [" + cluster.fork().process.pid + "]")
         } 
        
        // HERE
        require("/server")

         cluster.on('exit', function (worker) {
            log.error("Worker with ID: [" + worker.process.pid + "] died")
            setTimeout(function () { cluster.fork() }, 1000)
         })

And why is the error Error: bind EADDRINUSE given with
=>
if (cluster.isMaster) {
         var count = 0
         while(CPUs.length > count++) {
            log.debug("Worker booted with ID: [" + cluster.fork().process.pid + "]")
         } 
         //And
        require("/server")

         cluster.on('exit', function (worker) {
            log.error("Worker with ID: [" + worker.process.pid + "] died")
            setTimeout(function () { cluster.fork() }, 1000)
         })
      }else {
         //And
          require("/server")
      }

Let's say require("/server") =
var http = require("http")
  // Worker processes have a http server.
  http.Server(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");

    // notify master about the request
    process.send({ cmd: 'notifyRequest' });
  }).listen(8000);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Gusev, 2015-11-25
@SalimILE

And why is the error Error: bind EADDRINUSE thrown

Because the http server is launched in the cluster master and in the worker,
but the start in the worker fails, due to the fact that the port that it should listen to is already busy.
If you start the http server only in a worker, then in this case the master cluster plays the role of a load balancer, and the workers do not conflict with each other.
In your second example - just the workers are falling down because the port is occupied by the master
. What else does not work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question