← 中文资源

简体中文版本

Undici 自定义 Agent 连接池

用 undici Agent 固定每源站连接数与流水线深度,让复用连接的请求带显式中止超时,用完即关闭连接池。

阅读英文原文

示例说明

该示例面向高频调用外部 API 的 Node 服务。Node 全局默认分发器不限制连接数,流量突增时容易把下游服务打挂。通过自建 Agent,把并发连接与流水线深度约束在业务可承受范围内,keepAliveTimeout 控制空闲连接的回收节奏,请求级别再用 AbortController 提供硬超时兜底。

技术要点

  • connections 限制同源站并发 TCP 连接数
  • pipelining 允许单连接复用多个在途请求
  • AbortController 提供请求级显式超时

代码解读

代码先构造 Agent 并传入连接、流水线和保活参数;请求时通过 dispatcher 字段绑定该 Agent,并用 signal 接入 5 秒超时。请求完成后 clearTimeout 释放定时器,最后调用 agent.close() 关闭所有底层 socket,避免进程退出时被悬挂句柄阻塞。

使用建议

连接数应参考下游服务的承受能力,不要盲目调大。若访问多个不同源站,可按域名分别建 Agent 或使用 setGlobalDispatcher 统一托管。服务优雅停机时记得调用 close,否则 keep-alive 连接会拖住事件循环。

代码示例

import { Agent, fetch } from 'undici';

const agent = new Agent({
  connections: 128,
  pipelining: 10,
  keepAliveTimeout: 60_000,
  keepAliveMaxTimeout: 300_000,
});

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);

const res = await fetch('https://api.example.com/users', {
  dispatcher: agent,
  signal: controller.signal,
});
const users = await res.json();
clearTimeout(timer);

agent.close();