简体   繁体   English

Node.js集群示例

[英]Node.js Cluster Example

Can someone do an code example for me using node.js natives cluster? 有人可以使用node.js本机集群为我做一个代码示例吗?

Lets say I have this code and want each 'X' to be balanced between my cores, how would I do that? 可以说我有这段代码,希望每个“ X”在我的内核之间保持平衡,我该怎么做?

var y = {};
var i = 0;
var X = require('x.js');

wss.on('connection', function(ws) {

console.log("client connected sucessfully");

    ws.on('message', function(obj) {
        for(var a = 0; a < 100; a++){
            y[i] = new X();
            i++;
        }
    });
});

There's a good example on the node cluster documentation page . 节点集群文档页面上有一个很好的示例。 In short, you want to use cluster.fork() to create a new worker. 简而言之,您想使用cluster.fork()创建一个新的worker。 The worker will execute the same code that master does, so your example would become something like this: 该工作人员将执行与master相同的代码,因此您的示例将如下所示:

var y = {};
var i = 0;
var X = require('x.js');
if (cluster.isMaster) {
  for (var worker_num = 0; worker_num < 10; worker_num++) {
    cluster.fork();
  }
} else {
  wss.on('connection', function(ws) {
    console.log("client connected sucessfully");
      ws.on('message', function(obj) {
        for(var a = 0; a < 100; a++){
          y[i] = new X();
          i++;
        }
     });
  });
}

However in reality you would need way more than that. 但是实际上,您将需要的还不止这些。 You'd want features like automatic worker restarts, heartbeats, etc etc, so writing good cluster managing code is a big task by itself. 您需要自动重启工作程序,心跳等功能,因此编写良好的集群管理代码本身就是一项艰巨的任务。 I suggest using some ready solution pm2 or service-runner 我建议使用一些现成的解决方案pm2服务运行程序

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

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