【问题标题】:Requesting large JSON objects lead to memory leak请求大型 JSON 对象会导致内存泄漏
【发布时间】:2017-03-14 17:24:15
【问题描述】:

我有一个简单的 NodeJs 应用程序,它充当 REST 客户端并请求大型 JSON 对象。问题是它总是内存不足(占用超过 6Gb)。我正在使用手动垃圾收集(应用程序以 --expose_gc 开头),但这似乎没有多大帮助。

这是我的代码:

var needle = require('needle');
function getAllData() {
    getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
    getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
    getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
    getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
    getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");

    setInterval(function () {
        getAllData();
    }, 10 * 1000);
}

function getDataFromUrl(url) {
    needle.get(url, function (error, response) {
        if (!error && response.statusCode == 200) {
            console.log("do something");
        }
    });
}

function scheduleGc() {
    global.gc();
    setTimeout(function () {
        scheduleGc();
    }, 100 * 1000);
}

getAllData();
scheduleGc();

我尝试过请求库,但结果相同。我做错了什么?

附:我的nodejs版本是6.9.1,needle版本是1.3.0

【问题讨论】:

    标签: node.js memory-leaks needle.js


    【解决方案1】:

    这是因为您处理的信息太多,应该使用 处理 6Gb。
    使用 needle 非常简单,只需避免回调即可。
    这是一个例子:

    'use strict';
     const needle = require('needle');
     const fs = require('fs');
     const out = fs.createWriteStream('bigFile.json');
     needle.get('http://puppygifs.tumblr.com/api/read/json').pipe(out);
    

    【讨论】:

    • JSON 不是 6Gb,它要小得多。由于我使用的是 setInterval 而不是 setTimeout,因此 6Gb 是使用的 RAM 量...
    【解决方案2】:

    我发现了一个错误。我使用的是 setInterval 而不是 setTimeout....

    var needle = require('needle');
    function getAllData() {
        getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
        getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
        getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
        getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
        getDataFromUrl("http://puppygifs.tumblr.com/api/read/json");
    }
    
    function getDataFromUrl(url) {
        needle.get(url, function (error, response) {
            if (!error && response.statusCode == 200) {
                console.log("do something");
            }
        });
    }
    
    function scheduleGc() {
        global.gc();
    
        setTimeout(function () {
            scheduleGc();
        }, 100 * 1000);
    }
    
    setInterval(function () {
        getAllData();
    }, 10 * 1000);
    
    scheduleGc();
    

    【讨论】:

      【解决方案3】:

      使用节点检查器查找泄漏。它可能是内部 nodejs 泄漏或针和请求泄漏。我更喜欢使用原生 http.request 来确保它不是库问题。您也可以将您的代码拆分成独立的部分并单独运行以查找泄漏源。

      another answer如何检测内存泄漏。

      【讨论】:

        猜你喜欢
        • 2014-06-20
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 2015-03-08
        • 2021-02-26
        • 2021-03-23
        • 2021-09-25
        • 2014-12-08
        相关资源
        最近更新 更多