关于 dotnet-health-checks
用于配置 .NET 应用健康检查的技能,涵盖依赖项和自定义逻辑。内容包括存活与就绪检查,以及数据库、外部服务、缓存和消息代理的示例。
主要功能
- 01存活与就绪检查
- 02PostgreSQL 连通性检查
- 03HTTP 端点检查
- 04Redis 和 RabbitMQ 检查
- 05自定义应用健康检查
适用场景
- 01检查应用状态以决定流量路由
- 02监控 PostgreSQL 连通性
- 03检查外部 API 是否可用
- 04添加自定义数据库迁移检查
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ronnythedev/ dotnet-clean-architecture-skills --skill dotnet-health-checks安装后在 Claude Code 中输入/dotnet-health-checks确认已加载。
详细介绍
健康检查配置
概述
健康检查用于监控应用依赖项:
- 存活状态 - 应用是否正在运行?
- 就绪状态 - 应用是否已准备好处理流量?
- 数据库检查 - PostgreSQL 连接状态
- 外部服务检查 - API、缓存、队列
- 自定义检查 - 业务逻辑验证
快速参考
| 检查类型 | 用途 |
|---|---|
AddNpgSql | PostgreSQL 数据库 |
AddUrlGroup | 外部 HTTP 端点 |
AddRedis | Redis 缓存 |
AddRabbitMQ | RabbitMQ 消息代理 |
| 自定义 | 特定于应用的检查 |
模板:健康检查注册
// src/{name}.infrastructure/HealthChecks/HealthCheckExtensions.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace {name}.infrastructure.healthchecks;
public static class HealthCheckExtensions
{
public static IServiceCollection AddHealthChecks(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddHealthChecks()
// ═══════════════════════════════════════════════════════════════
// DATABASE
// ═══════════════════════════════════════════════════════════════
.AddNpgSql(
configuration.GetConnectionString("Database")!,
name: "postgresql",
failureStatus: HealthStatus.Unhealthy,
tags: new[] { "db", "sql", "postgresql", "ready" })
// ═══════════════════════════════════════════════════════════════
// EXTERNAL SERVICES
// ═══════════════════════════════════════════════════════════════
.AddUrlGroup(
new Uri(configuration["AuthService:BaseUrl"]!),
name: "auth-service",
failureStatus: HealthStatus.Degraded,
tags: new[] { "external", "auth", "ready" })
// ═══════════════════════════════════════════════════════════════
// REDIS (if used)
// ═══════════════════════════════════════════════════════════════
// .AddRedis(
// configuration.GetConnectionString("Redis")!,
// name: "redis",
// tags: new[] { "cache", "redis", "ready" })
// ═══════════════════════════════════════════════════════════════
// CUSTOM CHECKS
// ═══════════════════════════════════════════════════════════════
.AddCheck<DatabaseMigrationHealthCheck>(
"database-migrations",
tags: new[] { "db", "migrations", "ready" });
return services;
}
}
模板:自定义健康检查
// src/{name}.infrastructure/HealthChecks/DatabaseMigrationHealthCheck.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace {name}.infrastructure.healthchecks;
internal sealed class DatabaseMigrationHealthCheck : IHealthCheck
{
private readonly ApplicationDbContext _dbContext;
public DatabaseMigrationHealthCheck(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
var pendingMigrations = await _dbContext.Database
.GetPendingMigrationsAsync(cancellationToken);
var pending = pendingMigrations.ToList();
if (pending.Any())
{
return HealthCheckResult.Degraded(
$"Pending migrations: {string.Join(", ", pending)}",
data: new Dictionary<string, object>
{
{ "pending_count", pending.Count },
{ "migrations", pending }
});
}
return HealthCheckResult.Healthy("All migrations applied");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy(
"Failed to check migrations",
exception: ex);
}
}
}
模板:Program.cs 配置
// src/{name}.api/Program.cs
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
var app = builder.Build();
// ═══════════════════════════════════════════════════════════════
// LIVENESS: Is the app running?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false, // No checks, just confirms app is running
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
// ═══════════════════════════════════════════════════════════════
// READINESS: Is the app ready to serve traffic?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
// ═══════════════════════════════════════════════════════════════
// FULL: All health checks
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
Kubernetes 配置
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: api
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 10
periodSeconds: 30
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
相关技能
dotnet-clean-architecture- 基础设施层设置dotnet-jwt-authentication- 身份验证服务健康检查
评论
支持 Markdown