NodeJS集群全局变量

问题描述 投票:1回答:1

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

node.js multithreading cluster-computing
1个回答
2
投票

为此,您需要使用Node.js中提供的cluster模块在worker和master之间进行消息传递。

Example Code

这是我刚刚放在一起的一个工作示例。我正在使用官方网站(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}`);
    }
  });

}

Example Output

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

Official Documentation

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

© www.soinside.com 2019 - 2024. All rights reserved.