节点集群工作人员内存 [英] Node cluster workers memoryUsage

查看:82
本文介绍了节点集群工作人员内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否有一种独立于平台的方式来获取工作程序的内存使用情况吗?我希望它会像这样工作:

Does anyone know if there is a platform independent way to get memory usage of a worker? I would expect it would work like this:

console.log('App process memoryUsage: ',process.memoryUsage());
cluster.on('online',function(worker){    // doesn't work! 
  console.log('Workers memory usage: ',worker.process.memoryUsage());  
});

但是worker进程没有方法 memoryUsage().

But the workers process hasn't the method memoryUsage().

有没有正当的理由?

认识到这一点的唯一想法是在Linux上使用unix top -pid 1234 (macosx)或 top -p 1234 .并通过 process.plattform 进行切换.

The only idea to realize this is to work with unix top -pid 1234 (macosx) or top -p 1234 on linux. And switching by process.plattform.

推荐答案

是的,实际上您无法从worker的process属性中获取 memoryUsage .我不确定为什么没有实现它,但是您可以使用这种方法实现相同的目的:

Yes indeed you cannot get memoryUsage from worker's process property. I am not sure why it's not implemented, but you can achieve the same with this approach:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
  cluster.on('online', function(worker, code, signal) {
    worker.send('memoryUsage');
    worker.on('message', function(dd) {
      if (dd.event == 'memoryUsage') {
        console.log("Worker with ID: %d consumes %imb of memory", worker.id, dd.data.heapTotal / 1024 / 1024);
      }
    });
  });
  console.log("Master consumes %imb of memory", process.memoryUsage().heapTotal / 1024 / 1024);
} else {
  if (cluster.worker.id == 1) {
    a = [];
    for (var i = 0; i < 1000000; i++) {
      //just to see the difference in memory usage.
      a.push(Number.MAX_SAFE_INTEGER);
    };
  }
  process.on('message', function(msg) {
    if (msg == 'memoryUsage') {
      process.send({
        event: msg,
        data: process.memoryUsage()
      });
    }
  });
}

在8核系统上的输出:

user$ node ClusterTest.js 
Master consumes 6mb of memory
Worker with ID: 2 consumes 5mb of memory
Worker with ID: 6 consumes 5mb of memory
Worker with ID: 3 consumes 5mb of memory
Worker with ID: 4 consumes 5mb of memory
Worker with ID: 7 consumes 5mb of memory
Worker with ID: 5 consumes 5mb of memory
Worker with ID: 8 consumes 5mb of memory
Worker with ID: 1 consumes 39mb of memory
^C
user$

这篇关于节点集群工作人员内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆