簡體   English   中英

從master(Node.js集群)訪問工作線程環境

[英]Access worker environment from master (Node.js Cluster)

我通過Cluster模塊在我的Node.js應用程序中分工,並將自定義ID傳遞給我所有工作人員的環境。 到目前為止效果很好。

但是,當發出“在線”或“退出”事件時,我不知道如何在我的主人中訪問此ID。

文檔不是很有幫助。 你能指點我正確的方法嗎?

var cluster = require('cluster'); 

if (cluster.isMaster) {
  //MASTER

  function fork() {
    var worker_env = {worker_id:'my_custom_id'};
    cluster.fork(worker_env);
  }                 

  cluster.on('online', function(worker) {
    console.log(worker.process.env.worker_id); // undefined
    //
    // How can I access my custom worker id here?
    //
  });

  cluster.on('exit', function(worker, code, signal) {
    //
    // And here...?
    //
    fork();
  });

} else {
  // WORKER

  console.log(process.env.worker_id); // my_custom_id
}

沒有辦法,工作進程env不會暴露給主人。

一個aproach可以是我們的集群的映射(一個對象包含所需的信息)。

像這樣的東西:

var cluster = require('cluster');

if (true === cluster.isMaster) {
  //CODE EXECUTED BY MASTER
  var cluster_map = {}; // Here we store the workers info in a object   
  var restart_Limit = 10; // max global worker restart (10)

  function fork_worker(myWorkerId) {
    // these makes worker_id available in the worker
    var worker = cluster.fork({
      worker_id: myWorkerId 
    });
    // max restarts limit (global)
    if (worker.id >= restart_Limit) { 
      console.log('Restart limit reached, bye!');
      process.kill();

    }
    // here we add the key "myWorkerId"  to the cluster map
    cluster_map[worker.id] = myWorkerId;

    // WORKER AUTO-KILL
    setTimeout(function() {
      console.log('stoping...' + myWorkerId);
      worker.kill();
    }, 3000);
  }

  cluster.on('online', function(worker) {
    var online_proc = cluster_map[worker.id];

    console.log('worker online: ' + online_proc + '\n Restarts: ' + worker.id);
  });

  cluster.on('exit', function(worker, code, signal) {

    var exited_proc = cluster_map[worker.id];

    // delete the process from the cluster map
    delete cluster_map[worker.id];
    console.log("worker offline: " + exited_proc);

    // WORKER AUTO-RESTART
    setTimeout(function() {
      console.log('Restarting... ' + exited_proc);
      fork_worker(exited_proc);
    }, 3000);

  });

  // start the magic ( 3 workers )
  (function() {
    fork_worker('id_1');
    fork_worker('id_2');
    fork_worker('id_3');
  })();

} else {
  //CODE EXECUTED BY EACH WORKER (process env is present here).
  console.log('hi from the worker,  process.env: ' + process.env.worker_id);
  // all the hard work for the workers here.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM