在 NodeJS 中使用集群时无法让所有工作人员进入工作程序块

Posted

技术标签:

【中文标题】在 NodeJS 中使用集群时无法让所有工作人员进入工作程序块【英文标题】:Unable to get all workers in worker block while using cluster in NodeJS 【发布时间】:2019-08-04 00:10:08 【问题描述】:

我需要获取工作块中的所有工作人员 ID 列表。这是我的示例,它不起作用

const cluster = require('cluster');
var a = [];
if (cluster.isMaster) 
  console.log('I am master');
  cluster.fork();
  cluster.fork();
 else if (cluster.isWorker) 
  a.push(cluster.worker.id);
  console.log(`I am worker #$cluster.worker.id`);
  console.log(a);

输出:

I am master
I am worker #1
[ 1 ]
I am worker #2
[ 2 ]

预期输出

I am master
I am worker #1
[ 1 ]
I am worker #2
[ 1, 2 ]

【问题讨论】:

【参考方案1】:

因为您的代码从一开始就执行了 3 次,所以每个变量对于每个工作人员来说都是唯一的。想象一下正在运行 3 个不同的应用程序,它们彼此不共享变量。

worker 1 上的变量a 与worker 2 中的a 不同。

如果你想共享信息,你可以使用数据库、持久存储,或者尝试在主从之间创建一个通信通道。

以下是主从之间通信的示例:

const cluster = require('cluster');
var a = [];

function onNewWorker(workers) 
    a = workers;
    console.log(`I am worker #$cluster.worker.id, all workers = $a`);


if (cluster.isMaster) 
    cluster.on("fork", (worker) => 
        a.push(worker);
        a.forEach(w => w.send(a.map(wr => wr.id)));
    );
    console.log('I am master');
    const proc1 = cluster.fork();
    const proc2 = cluster.fork();
 else if (cluster.isWorker) 
    a.push(cluster.worker.id);
    process.on("message", onNewWorker);
    console.log(`I am worker #$cluster.worker.id`);
    console.log(a);

输出

I am master
I am worker #1
I am worker #2
[ 1 ]
[ 2 ]
I am worker #1, all workers = 1
I am worker #1, all workers = 1,2
I am worker #2, all workers = 1,2

当然你可以改进这段代码,这只是一个例子。

【讨论】:

【参考方案2】:

Documentation about cluster

工作进程是使用 child_process.fork() 方法生成的


当你分叉一个进程时,会创建一个新进程,它是实际进程的严格副本(变量...)。它们在每个过程变量之间没有关系。

新进程将从调用fork() 函数的行(代码)开始。

Definition of fork

【讨论】:

以上是关于在 NodeJS 中使用集群时无法让所有工作人员进入工作程序块的主要内容,如果未能解决你的问题,请参考以下文章

NodeJS 不使用 express 返回 JSONP

我无法让 Pulsar 集群正确重启

无法让 pyspark 作业在 hadoop 集群的所有节点上运行

nodejs - 无法让 paypal-ipn 工作。 Paypal 不断返回“无效”

无法让 CORS 工作(NodeJS)

使用bcrypt在nodejs中进行密码加密