简体   繁体   English

NodeJS集群全局变量

[英]NodeJS cluster global variables

I need to have one common counter for all workers, and everyone could increase it, and that all workers know that the counter has been increased. 我需要为所有工人建立一个共同的柜台,每个人都可以增加它,而且所有工人都知道柜台已经增加。 How can i do that ? 我怎样才能做到这一点 ? All workers can see only local variabless , and only static global variabless. 所有工作人员只能看到局部变量,只能看到静态全局变量。

To accomplish this, you will want to use the cluster module available in Node.js to message between the workers and the master. 为此,您将需要使用Node.js中可用的cluster模块在辅助服务器和主服务器之间发送消息。

Example Code 范例程式码

Here is a working example I just put together. 这是我刚刚整理的一个工作示例。 I am using the latest version of Node.js available on the official website ( 9.3.0 ). 我正在使用官方网站( 9.3.0 )上的最新版本的9.3.0

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]) 这是worker.send(message[, sendHandle][, callback])的文档worker.send(message[, sendHandle][, callback])

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

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