new Agent([options])
options<Object> 一组可在代理上设置的可配置选项。可以包含以下字段:keepAlive<boolean> 即使没有未完成的请求,也要保留套接字,以便将来可以用于请求,而无需重新建立 TCP 连接。不要与Connection头的keep-alive值混淆。使用代理时总是会发送Connection: keep-alive头,除非明确指定了Connection头,或者分别将keepAlive和maxSockets选项设置为false和Infinity,在这种情况下将使用Connection: close。默认值:false。keepAliveMsecs<number> 使用keepAlive选项时,指定 TCP Keep-Alive 数据包的 初始延迟。当keepAlive选项为false或undefined时将被忽略。默认值:1000。maxSockets<number> 每个主机允许的最大套接字数量。如果同一主机打开多个并发连接,每个请求将使用新的套接字,直到达到maxSockets值。如果主机尝试打开的连接数超过maxSockets,额外的请求将进入待处理请求队列,并在现有连接终止后进入活动连接状态。这确保了在任何时间点,每个主机最多只有maxSockets个活动连接。默认值:Infinity。maxTotalSockets<number> 允许所有主机总共使用的最大套接字数量。每个请求将使用一个新的套接字,直到达到最大值。 默认值:Infinity。maxFreeSockets<number> 每个主机允许保持空闲状态的最大套接字数量。仅在keepAlive设置为true时相关。默认值:256。scheduling<string> 选择下一个可用套接字时要应用的调度策略。可以是'fifo'或'lifo'。这两种调度策略的主要区别在于,'lifo'选择最近使用的套接字,而'fifo'选择最不常使用的套接字。如果每秒请求率较低,'lifo'调度可以降低选择已因不活动而被服务器关闭的套接字的风险。如果每秒请求率较高,'fifo'调度将最大化打开套接字的数量,而'lifo'调度将其保持在尽可能低的水平。默认值:'lifo'。timeout<number> 套接字超时(毫秒)。这将设置创建套接字时的超时。
socket.connect() 中的 options 也受支持。
http.request() 使用的默认 http.globalAgent 已将所有这些值设置为各自的默认值。
🌐 The default http.globalAgent that is used by http.request() has all
of these values set to their respective defaults.
要配置其中的任何一个,必须创建一个自定义的 http.Agent 实例。
🌐 To configure any of them, a custom http.Agent instance must be created.
import { Agent, request } from 'node:http';
const keepAliveAgent = new Agent({ keepAlive: true });
options.agent = keepAliveAgent;
request(options, onResponseCallback);const http = require('node:http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);