简体   繁体   English

如何在Node.js中设置两个意图不同的工作程序?

[英]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. 设置工作程序,但是说如果我希望两台服务器在不同的端口上运行,而在发生错误时一台服务器不关闭另一台服务器,那么可能的方法是仅允许使用cluster进行这种设置。

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. 如果您希望其他工作人员执行不同的工作,则只需使用child_process模块​​以诸如child_process.fork()类的方式启动您的工作人员,为他们提供不同的代码,并使用可用于您与工作人员进行通信的任何数量的通信方法。 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. 例如,每个工作人员可以在其端口上启动其自己的http服务器,然后可以从该端口上的主进程与之通信。

Here's a simple .fork() example that illustrates using process message for communicating between the two. 这是一个简单的.fork()示例,该示例说明了如何使用进程消息在两者之间进行通信。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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