.NET健康检查通过/health端点监控服务状态,支持数据库、Redis等依赖检测,结合Kubernetes探针实现自动流量管理与容器重启,提升微服务稳定性。

.NET中的健康检查(Health Checks)是一种用于监控应用程序运行状态的机制,帮助外部系统(如负载均衡器、Kubernetes 或服务网格)判断某个服务实例是否正常运行。它不只检查应用是否启动,还能检测其依赖项(如数据库、缓存、消息队列等)是否可用。
健康检查通常通过一个公开的HTTP端点(如 /health)暴露服务状态。该端点返回一个简短的状态信息,常见状态包括:
Kubernetes 等编排工具会定期调用这个接口,自动决定是否将流量路由到该实例或重启容器。
在 .NET(尤其是 ASP.NET Core)中,可以通过 Microsoft.Extensions.Diagnostics.HealthChecks 包实现健康检查功能。以下是具体步骤:
例如,检查 SQL Server:
Install-Package Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore
示例代码:
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>() // 检查数据库上下文
.AddRedis("redisConnectionString", name: "redis") // 检查 Redis
.AddUrlGroup(new Uri("https://api.external.com/health"), name: "external-api");
// 启用健康检查中间件
app.MapHealthChecks("/health");
app.MapHealthChecks("/health-details", new HealthCheckOptions()
{
ResponseWriter = WriteDetailedResponse // 输出详细信息(谨慎用于生产)
});
生产环境建议只暴露简洁状态,避免泄露敏感信息。调试环境可开启详细输出:
static Task WriteDetailedResponse(HttpContext context, HealthReport report)
{
context.Response.ContentType = "application/json";
var response = new
{
Status = report.Status,
Checks = report.Entries.Select(e => new
{
e.Key,
e.Value.Status,
e.Value.Description
})
};
return context.Response.WriteAsJsonAsync(response);
}
在 Kubernetes 中,可通过 liveness 和 readiness 探针使用健康检查端点:
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 5
periodSeconds: 5
对于特定业务逻辑,可以实现自定义检查:
public class CustomHealthCheck : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
// 自定义逻辑:比如检查磁盘空间、外部服务凭证等
var isHealthy = await SomeBusinessCondition();
if (isHealthy)
return HealthCheckResult.Healthy("Custom check passed.");
return HealthCheckResult.Unhealthy("Custom check failed.");
}
}
注册时使用:
services.AddHealthChecks().AddCheck<CustomHealthCheck>("custom");基本上就这些。.NET 的健康检查机制轻量、灵活,非常适合微服务架构中的可观测性需求。合理配置后,能显著提升系统的稳定性和运维效率。
以上就是.NET中的健康检查(Health Checks)是什么?如何在微服务中实现它?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号