how to keep variables that share all node processes in node cluster?

前端 未结 6 1953
离开以前
离开以前 2021-02-02 12:17

It seems like all the node woker processes are working as if it is executing a new copy of the same application. But would like to keep some variables that are shared by all nod

6条回答
  •  暖寄归人
    2021-02-02 12:28

    You can try to communicate between master process and child processes. For example:

    script test.master.js:

    var cluster = require('cluster');
    var childScript = __dirname + '/test.child.js';
    
    cluster.setupMaster({ exec: childScript });
    
    proc = cluster.fork();
    proc.on('message', function(message) {
        console.log('message from child: ', message);
        proc.send('Hello from master!');
    });
    

    script test.child.js:

    console.log('Child initializing..');
    
    process.on('message', function(message) {
        console.log('message from master: ', message);
    });
    
    process.send('Hello from Child!');
    

提交回复
热议问题