关于NestJS应用发起外部出站请求时默认是否启用Keep-Alive的技术咨询
NestJS应用发起外部出站请求时默认是否启用Keep-Alive?
嘿,针对你的问题,直接给你明确结论:在你当前使用的NestJS(@nestjs/core ^9.0.9、@nestjs/axios ^3.0.1)和Axios(1.8.2)版本中,应用发起的外部出站请求默认是不启用Keep-Alive的。
原因很简单:NestJS的HttpModule本质就是Axios的一层封装,它完全沿用了Axios的默认配置规则——而Axios本身的默认请求配置里,keepAlive参数是默认设为false的,不会自动启用连接复用。你提到的代码示例里,直接通过this.httpService.post()发起请求时,用的就是这套默认配置,所以Keep-Alive是关闭状态。
如果你的业务场景需要启用Keep-Alive来优化连接复用,有两种常见的配置方式:
1. 全局配置HttpModule
在模块导入时统一设置Agent,让所有通过HttpService发起的请求都启用Keep-Alive:
import { Module } from '@nestjs/common'; import { HttpModule } from '@nestjs/axios'; @Module({ imports: [ HttpModule.register({ httpAgent: new (require('http').Agent)({ keepAlive: true }), httpsAgent: new (require('https').Agent)({ keepAlive: true }), }), ], }) export class AppModule {}
2. 单个请求单独配置
如果只需要特定请求启用Keep-Alive,可以在请求时传入自定义配置:
private async fetchStudentDetails(studentIds: string[], targetUrl: string): Promise<Map<string, object>> { const response = await this.httpService.post( targetUrl, { studentIds }, { httpAgent: new (require('http').Agent)({ keepAlive: true }), httpsAgent: new (require('https').Agent)({ keepAlive: true }), } ).toPromise(); // 这里处理你的响应数据,生成Map返回 const studentMap = new Map<string, object>(); // 假设响应数据是response.data.students数组,格式为{ id: string, details: object } response.data.students.forEach(student => { studentMap.set(student.id, student.details); }); return studentMap; }
内容来源于stack exchange
相关产品推荐
相关产品推荐

