健康检查
系统健康检查框架,监控应用和基础设施状态
概述
@mono/health 提供可扩展的健康检查框架,支持数据库连接、外部服务、自定义检查,并生成标准 HTTP 响应。
安装
pnpm add @mono/health实战示例
1. 基础健康检查 API
import { checkHealth, createDbChecker, healthResponse } from "@mono/health";
import { prisma } from "@/lib/db";
export async function GET() {
const result = await checkHealth({
checkers: [
createDbChecker(() => prisma.$queryRaw`SELECT 1`),
],
});
return healthResponse(result);
}
export async function HEAD() {
return new Response(null, { status: 200 });
}2. 多服务检查
import { checkHealth, createDbChecker, createChecker, healthResponse } from "@mono/health";
export async function GET() {
const result = await checkHealth({
checkers: [
createDbChecker(() => prisma.$queryRaw`SELECT 1`),
createChecker("redis", async () => {
const redis = getRedisClient();
await redis.ping();
}),
createChecker("storage", async () => {
const res = await fetch(process.env.S3_ENDPOINT + "/health");
if (!res.ok) throw new Error("Storage unavailable");
}),
],
timeout: 3000,
});
return healthResponse(result);
}3. 监控集成
import { checkHealth, createDbChecker } from "@mono/health";
export async function runHealthCheck() {
const result = await checkHealth({
checkers: [
createDbChecker(() => prisma.$queryRaw`SELECT 1`),
],
});
if (result.status === "unhealthy") {
// 发送告警
await sendAlert({
title: "服务不健康",
details: JSON.stringify(result.checks, null, 2),
memory: result.system?.memory,
});
}
return result;
}4. 自定义检查器
import { createChecker } from "@mono/health";
// 检查外部 API
const apiChecker = createChecker("external-api", async () => {
const res = await fetch("https://api.stripe.com/v1/health");
if (!res.ok) throw new Error(`Stripe API: ${res.status}`);
});
// 检查磁盘空间
const diskChecker = createChecker("disk", async () => {
const { execSync } = await import("child_process");
const usage = execSync("df -h / | tail -1").toString();
const percent = parseInt(usage.match(/(\d+)%/)?.[1] || "0");
if (percent > 90) throw new Error(`Disk usage: ${percent}%`);
});API 参考
checkHealth(options?)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
includeSystem | boolean | true | 包含系统信息 |
timeout | number | 5000 | 每个检查的超时(ms) |
checkers | HealthChecker[] | [] | 检查器列表 |
HealthCheckResult
| 字段 | 类型 | 说明 |
|---|---|---|
status | "healthy" | "degraded" | "unhealthy" | 整体状态 |
timestamp | string | ISO 8601 时间戳 |
uptime | number | 运行时间(秒) |
checks | Record<string, CheckResult> | 各检查结果 |
system | SystemInfo | 系统信息(可选) |
healthResponse(result)
将结果转为 HTTP Response。healthy 返回 200,其他返回 503。
最佳实践
建议为健康检查端点设置独立的超时,避免检查本身导致请求超时。
- HEAD 方法 — 添加 HEAD 处理器用于轻量级存活探针
- 超时设置 — 每个检查器设置合理超时,默认 5 秒
- 缓存控制 —
healthResponse自动添加 no-cache 头 - 告警集成 — 结合 cron 或监控服务定期检查
相关文档
- @mono/logs — 日志系统
- @mono/cache — 缓存层