简体   繁体   中英

How to set up two workers in Node.js with different intentions?

Traditionally I use:

if (cluster.isMaster) {
  cluster.fork();
  cluster.on('exit', function(worker, code, signal) {
    cluster.fork();
  });
}
if (cluster.isWorker) {
  ...
}

to setup workers but say if I want two servers running at different port without one server shutting down another when an error occur, what might be the method to allow such setup using cluster only.

For workers with different jobs to do, don't use clustering at all. Clustering is for multiple processes that share a port and incoming work is load balanced equally among all in the cluster.

If you want some other workers that do different jobs, then just use the child_process module to start your workers with something like child_process.fork() , give them different code and use any number of communication methods available to you to communicate with the workers. For example, each worker can start its own http server on its port and then you can communicate with it from the main process on that port.

Here's a simple .fork() example that illustrates using process message for communicating between the two. You can use many other communication mechanisms too.

Parent code:

const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

Child code:

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

let counter = 0;

setInterval(() => {
  process.send({ counter: counter++ });
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM