NestJS健康检查端点
“在NestJS中如何设置健康检查端点?我尝试使用@nestjs/throttler和Terminus模块,但端点总是返回404错误。文档中说需要注册HealthCheckModule,但具体应该在AppModule还是子模块中导入?有没有完整的配置示例?另外,如何自定义检查项比如数据库连接状态和Redis服务可用性?如果某些依赖服务不可用,怎样才能让端点返回部分失败(503)而不是完全崩溃?求最佳实践方案。”
3 回复
在NestJS中实现健康检查端点非常简单。首先安装@nestjs/terminus
模块,它是基于Spring Actuator的健康检查工具。
- 安装依赖:
npm install @nestjs/terminus
- 创建健康检查模块:
import { Module } from '@nestjs/common';
import { HealthCheckController } from './health-check.controller';
@Module({
controllers: [HealthCheckController],
})
export class HealthCheckModule {}
- 在控制器中添加健康检查逻辑:
import { Controller, Get, Query } from '@nestjs/common';
import { HealthCheckService, HealthCheckExecutionResponse, HealthIndicatorResult } from '@nestjs/terminus';
@Controller('health')
export class HealthCheckController {
constructor(private health: HealthCheckService) {}
@Get()
check(@Query('ready') ready?: boolean): Promise<HealthCheckExecutionResponse> {
if (ready) {
return this.health.check([
async () => this.health.database('db', () => true),
]);
}
return this.health.check([]);
}
}
这样就实现了基本的健康检查和就绪检查功能。访问/health
获取健康状态,/health?ready=true
获取就绪状态。
在NestJS中创建健康检查端点非常简单。首先安装@nestjs/terminus
模块,它提供了健康检查的功能。
npm install @nestjs/terminus
然后,在你的模块中导入TerminusModule
:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TerminusModule } from '@nestjs/terminus';
@Module({
imports: [TerminusModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
接下来,在控制器中定义健康检查的路由:
import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HealthCheckExecutionResult } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(private healthCheckService: HealthCheckService) {}
@Get()
getHealth(): Promise<HealthCheckExecutionResult> {
return this.healthCheckService.check();
}
}
这样,你就有了一个基本的健康检查端点/health
。你可以进一步自定义检查逻辑,比如数据库连接、外部API等。通过这种方式,你可以轻松地为你的应用添加健康检查功能。
在NestJS中,健康检查可以使用官方提供的@nestjs/throttler
模块实现。这里简单介绍如何设置:
- 首先安装依赖:
npm install @nestjs/throttler
- 在AppModule中导入:
import { TerminusModule } from '@nestjs/terminus';
@Module({
imports: [TerminusModule],
controllers: [HealthController]
})
export class AppModule {}
- 创建健康检查控制器:
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(private health: HealthCheckService) {}
@Get()
@HealthCheck()
check() {
return this.health.check([
() => Promise.resolve({ status: 'ok' }),
]);
}
}
访问/health
端点将返回:
{
"status": "ok",
"info": {"status": "ok"},
"error": {},
"details": {"status": "ok"}
}
如果需要更复杂的检查(如数据库连接),可以注入相关服务并添加检查逻辑。这是NestJS推荐的健康检查实现方式。