node.js http请求在5次请求后锁定

node.js http request lock-up after 5 requests

本文关键字:请求 锁定 5次 http node js      更新时间:2023-10-20

我有一些非常简单的代码,如下所示:

var http = require('http');
var options = {
    hostname: 'google.com',
    port: 80,
    path: '/'
};
function makeRequest() {
    http.get(options, function(res) {
        console.log('Got response code: ', res.statusCode);
        process.nextTick(makeRequest);
    }).on('error', function(err) {
            console.error('Got error: ', err);
            throw err;
        });
}
makeRequest();

并且在5次请求之后,它锁定并停止工作。样本输出:

Got response code:  200
Got response code:  200
Got response code:  200
Got response code:  200
Got response code:  200
Got error:  { [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

查看hyperquest自述,它准确地解释了这里发生的事情,@substack为什么讨厌它,以及hyperquest如何避免它。

默认情况下,客户端连接被池化,空闲超时时间为2分钟,默认最大池大小为5。

如果您不打算重用实例化的代理,您应该在使用它之后调用destroy()方法,避免在池中保持空闲连接。示例:

var req = http.request({path: "/", host: "google.com",method: "HEAD"})
req.end();
req.on("response",function(res) {
    //do something
    // ....
    req.destroy();         
    //do other things
});