跳转到内容

健康检查

HealthModule 聚合 Prisma、Redis 及自定义检查指示器的健康状态,提供统一的健康检查端点。

安装

HealthModule 内置于 @maxtan/nest-core,无需额外安装。

基础用法

typescript
import { Module } from '@nestjs/common'
import { HealthModule, PrismaModule, CacheModule } from '@maxtan/nest-core'

@Module({
  imports: [
    PrismaModule.forRoot({ service: PrismaService }),
    CacheModule.forRoot({ host: 'localhost', port: 6379 }),
    HealthModule.forRoot(),
  ],
})
export class AppModule {}

启动后访问 GET /health

json
{
  "status": "ok",
  "components": {
    "prisma": { "status": "up", "duration": 3 },
    "redis": { "status": "up", "duration": 1 }
  },
  "duration": 5
}

配置选项

typescript
HealthModule.forRoot({
  path: 'status',        // 自定义端点路径,默认 'health'
  global: true,          // 是否全局注册,默认 true
  indicators: [          // 自定义检查指示器
    {
      name: 'external-api',
      check: async () => {
        const res = await fetch('https://api.example.com/ping')
        if (!res.ok) throw new Error('API 不可达')
      }
    }
  ]
})
选项类型默认值说明
pathstring'health'健康检查端点路径
globalbooleantrue是否全局注册
indicatorsHealthIndicator[][]自定义检查指示器

自动检测

HealthModule 自动检测已注册的服务:

  • PrismaModule 已注册 → 自动检查数据库连通性(SELECT 1
  • CacheModule 已注册 → 自动检查 Redis 连通性
  • 未注册的服务会被跳过,不会报错

多数据源

如果注册了多个 PrismaService,健康检查会分别检测:

json
{
  "status": "ok",
  "components": {
    "prisma-0": { "status": "up", "duration": 3 },
    "prisma-1": { "status": "up", "duration": 5 },
    "redis": { "status": "up", "duration": 1 }
  }
}

在代码中使用

除了 HTTP 端点,你也可以在代码中注入 HealthService

typescript
import { Injectable } from '@nestjs/common'
import { HealthService } from '@maxtan/nest-core'

@Injectable()
export class StartupService {
  constructor(private readonly health: HealthService) {}

  async onApplicationBootstrap() {
    const result = await this.health.check()
    if (result.status === 'error') {
      console.error('健康检查失败:', result.components)
    }
  }
}

Kubernetes 探针配置

yaml
livenessProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 10
  periodSeconds: 30

readinessProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 5
  periodSeconds: 10

响应格式

正常

json
{
  "status": "ok",
  "components": {
    "prisma": { "status": "up", "duration": 3 },
    "redis": { "status": "up", "duration": 1 }
  },
  "duration": 5
}

异常

json
{
  "status": "error",
  "components": {
    "prisma": { "status": "up", "duration": 3 },
    "redis": {
      "status": "down",
      "duration": 5001,
      "message": "Connection timeout"
    }
  },
  "duration": 5003
}

最佳实践

  1. 放在模块列表最后HealthModule.forRoot() 应在所有其他模块之后注册,以便自动检测已注册的服务
  2. 配置 K8s 探针:生产环境必须配置 livenessProbereadinessProbe
  3. 公开健康端点:使用 @AuthPublic() 标记健康检查路由,避免探针被认证拦截
  4. 自定义指示器:对关键外部依赖(如第三方 API、消息队列)添加自定义检查

相关文档