为什么这个Node Express代码导致内存泄漏和尖峰?

时间:2018-01-10 21:18:04

标签: javascript node.js express kue

我是JS / Express / Node / Kue的新手(使用Forever保持运行)。我接受了这个代码库,这导致我们的EC2实例每6小时将CPU利用率提高到100%。使用量从08UTC的0%稳定增长至14UTC的100%至20UTC的0%至08UTC的100%。这种情况不停发生,所以看起来像丘陵谷山谷。

奇怪的是,对于这项业务,在这个应用程序的晚上10点到早上8点之间有0个活动。

我正在查看代码,主要是发布请求。我看到一些未标记为var的参数使得它成为一个全局对象正确吗?想知道这些是不是被销毁了? initMe函数填充了未标记为vars的对象。我查看了其他POST代码,但他们也没有删除post_optionspost_options

jobs.process('notify_me', 50, function(job, done){
  var token = null;
  var ems_id = null;
  var title = null;
  var message = null;
  var type = null;
  var websocket_server = null;
  var payload = null;

  function initMe(){
    logMe("Got the following from payload: " + JSON.stringify(job));
    ems_id = job.data.ems_id;
    logMe("ems_id: " + ems_id);
    title = job.data.title;
    logMe("title: " + title);
    message = job.data.message;
    logMe("message: " + message);
    type = job.data.type;
    logMe("type: " + type);
    websocket_server = job.data.websocket_server;
    logMe("websocket_server: " + websocket_server);
    payload = {'title': title, 'message': message, 'type': type}

    login();
  }

  function displayTime() {
    var str = "";

    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    var seconds = currentTime.getSeconds()

    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    str += hours + ":" + minutes + ":" + seconds;
    return str;
  }

  function logMe(str){
    console.log(displayTime() + " : " + str);
    job.log(displayTime() + " : " + str);
  }

  function login(){
    logMe("start login");
    params = {
      api_key: ***,
      email: ********,
      password: *******
    };
    var post_data = querystring.stringify(params);
    var post_options = {
        hostname: DOMAIN,
        port: 443,
        path: "/v1/login_bot",
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': post_data.length
        }
    };
    var post_req = https.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        token = JSON.parse(chunk).token;
        logMe("retrieved token: " + token);
        notifyME();
      });
    });
    post_req.write(post_data);
    post_req.end();
  }

  function notifyME(){
    logMe("connecting to " + websocket_server);
    var socket = io.connect(websocket_server, {'force new connection': true});
    socket.on('connect', function(){
      logMe("notifying ems: " + ems_id);
      socket.emit('notify_me', 'ems_' + ems_id, JSON.stringify({payload: payload}));
      socket.disconnect();
    });
    done();
  }

  initMe();
});

0 个答案:

没有答案