javascript - Access worker environment from master (Node.js Cluster) -


I have your node through the cluster module. In the JS application, I pass a custom ID for the workers of the fork workers and the environment of all their workers. It works so far as well.

However, I do not know how an 'online' or 'exit' event is emitted when I can use this ID in my master.

The document is not very useful, can you tell me the right way?

  var requires cluster = ('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, hint) // // here ...? // Fork ();}); } Else {// WORKER console.log (process.env.worker_id); // my_custom_id}  

There is no way, the worker process env does not appear Is the master

An approach can be a map of our cluster (must contain the necessary information for an object).

Something like this:

  var cluster = required ('cluster'); If (true === cluster.isMaster) {// code executed by master work cluster_map = {}; // Here we store workers in an object var restart_Limit = 10; // Maximum global worker restart (10) function fork_worker (myWorkerId) {// This worker creates workers available in worker worker = cluster.fork ({worker_id: myWorkerId}); // Maximum restart limit (global) if (worker.id> = restart_Limit) {console.log ('reached restart limit, bye!'); Process.kill (); } // Here we add the key "myWorkerId" to the cluster map cluster_map [worker.id] = myWorkerId; // Worker auto-time settimeout (function () {console.log ('stop ...' + 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]; // Removing process from cluster maps Cluster_map [worker.id]; console.log ("Worker offline: "+ Exited_proc); // Worker Auto-Restart Set Timeout (function () {console.log ('restart ...' + exited_proc); fork_worker (exited_proc);}, 3000);}); // Start 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 available here) Console.log ('Hello from the worker, process.env:' + process.env.worker_id); // All the hard work for the workers here }  

Comments