繁体   English   中英

Node.js http.请求保活

[英]Node.js http.request keepAlive

我正在尝试在 http.request 上使用http.request http.Agent({ keepAlive: true})来为将来的请求保持连接打开。

我创建了一个简单的服务器来记录每个新连接,但是当我运行我的request.js时,服务器会记录两个新连接。

如何将 HTTP keep-alive 与 Node.js 本机模块一起使用?

请求.js:

const http = require("http");

const agent = new http.Agent({
    keepAlive: true
});

var req1 = http.request({
    agent: agent,
    method: "GET",
    hostname: "localhost",
    port: 3000
}, function (res1) {
    console.log("REQUEST_1");

    var req2 = http.request({
        agent: agent,
        method: "GET",
        hostname: "localhost",
        port: 3000
    }, function (res2) {
        console.log("REQUEST_2");
    });

    req2.end();
});

req1.end();

服务器.js:

const http = require('http');

var server = http.createServer(function (req, res) {
    res.end('OK');
    console.log("REQUEST");
})

server.on('connection', function (socket) {
    console.log("NEW CONNECTION");
})

server.listen(3000);

output:

NEW CONNECTION
REQUEST
NEW CONNECTION
REQUEST

像这样设置maxSockets选项:

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1
});

默认情况下maxSockets设置为Infinity - https://nodejs.org/api/http.html#http_new_agent_options

节点 v10 上的完整示例

const http = require("http");

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 1
});

var req1 = http.request({
    agent: agent,
    method: "GET",
    hostname: "localhost",
    port: 3000
}, function (res1) {
    console.log("REQUEST_1");

    res1.on('data', function () {
        console.log("REQUEST_1 data");
    });

    res1.on('end', function () {
        console.log("REQUEST_1 end");
    });

    var req2 = http.request({
        agent: agent,
        method: "GET",
        hostname: "localhost",
        port: 3000
    }, function (res2) {
        console.log("REQUEST_2");

        res2.on('data', function () {
            console.log("REQUEST_2 data");
        });

        res2.on('end', function () {
            console.log("REQUEST_2 end");
        });
    });
    req2.end();
});
req1.end();

接受的答案并没有明确表示发布的代码将只允许每个主机每个线程同时发出一个请求。

这通常不是您想要的,并且会导致请求变慢,等待前一个完成。

从 Node.js v19 开始,所有传出 HTTP(s) 连接的keepAlive选项默认设置为 true。

您可以在Node.js 的 v19 文档上阅读更多相关信息。

你的演示没有在data监听器上设置res1,它会导致套接字不关闭,所以第二个请求必须创建一个新的连接到服务器,只需添加一个data监听器

暂无
暂无

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

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