NodeJS集群全局变量

时间:2017-12-28 15:35:49

标签: node.js multithreading cluster-computing

我需要为所有工人配备一个共同的柜台,每个人都可以增加它,并且所有工人都知道柜台已经增加了。 我怎样才能做到这一点 ? 所有工作人员只能看到局部变量,而只能看到静态全局变量。

1 个答案:

答案 0 :(得分:2)

要实现此目的,您需要使用Node.js中提供的cluster模块在​​工作人员和主人之间发送消息。

示例代码

这是我刚刚放在一起的一个工作示例。我正在使用官方网站(9.3.0)上提供的最新版Node.js。

const cluster = require('cluster');
const INCREMENT = 'INCREMENT';
const COUNTER = 'COUNTER';


if (cluster.isMaster) {

  cluster.fork();
  cluster.fork();

  let counter = 0;

  cluster.on('message', (worker, msg, handle) => {
    if (msg.topic && msg.topic === INCREMENT) {
      // here we increment the counter
      counter++;
      for (const id in cluster.workers) {
        // Here we notify each worker of the updated value
        cluster.workers[id].send({
          topic: COUNTER,
          value: counter
        });
      }
    }
  });

} else if (cluster.isWorker) {

  console.log(`Worker id: ${cluster.worker.id}`);
  // Here is a function that requests the counter be updated in the master from a worker.
  function incrementCounter() {
    process.send({ topic: INCREMENT });
  }

  // A dummy timeout to call the incrementCounter function
  setTimeout(incrementCounter, 1000 * cluster.worker.id);

  // Handle the counter update
  process.on('message', (msg) => {
    if (msg.topic && msg.topic === COUNTER) {
      console.log(`${cluster.worker.id}/${process.pid}: ${msg.topic} ${msg.value}`);
    }
  });

}

示例输出

Worker id: 1
Worker id: 2
1/1632: COUNTER 1
2/6200: COUNTER 1
2/6200: COUNTER 2
1/1632: COUNTER 2

官方文件

Here is the documentation for worker.send(message[, sendHandle][, callback])