陈玉滢:铁骨铮铮的巾帼玫瑰,守护城市脉搏的铿锵玫瑰
.NET Core Web 中的健康检查端点文章目录.NET Core Web 中的健康检查端点概述核心概念
健康状况状态
主要组件基本配置
添加健康检查服务
配置端点路由创建自定义健康检查实现 IHealthCheck 接口常用内置健康检查
数据库健康检查
URL 健康检查
内存检查高级配置选项
分组和过滤
自定义响应格式
延迟启动和超时设置Kubernetes 集成示例
Pod 配置
应用程序配置健康检查 UI
安装包
配置最佳实践
分离检查类型
设置适当的超时
避免昂贵的操作
安全性考虑监控和警报
集成 Prometheus
集成 Application Insights示例完整配置
总结概述健康检查端点是 ASP.NET Core 提供的一种机制用于监控应用程序的运行状况通常用于容器编排如Kubernetes、负载均衡器和监控系统。
它允许外部系统定期检查应用程序是否正常运行并能够处理请求。
核心概念
健康状况状态Healthy应用程序正常运行Degraded应用程序运行但性能下降Unhealthy应用程序无法正常运行
主要组件IHealthCheck接口定义健康检查逻辑健康检查中间件处理健康检查请求健康检查服务注册和管理检查项基本配置
添加健康检查服务// Program.cs 或 Startup.cspublicvoidConfigureServices(IServiceCollectionservices){// 添加基本健康检查services.AddHealthChecks();// 或者添加自定义检查services.AddHealthChecks().AddCheckDatabaseHealthCheck(database).AddCheckExternalApiHealthCheck(external_api,failureStatus:HealthStatus.Degraded);}
配置端点路由publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){app.UseRouting();app.UseEndpoints(endpoints{// 基本健康检查端点endpoints.MapHealthChecks(/health);// 带自定义配置的端点endpoints.MapHealthChecks(/health/detailed,newHealthCheckOptions{ResponseWriterWriteResponse});});}创建自定义健康检查实现 IHealthCheck 接口publicclassDatabaseHealthCheck:IHealthCheck{privatereadonlystring_connectionString;publicDatabaseHealthCheck(IConfigurationconfiguration){_connectionStringconfiguration.GetConnectionString(DefaultConnection);}publicasyncTaskHealthCheckResultCheckHealthAsync(HealthCheckContextcontext,CancellationTokencancellationTokendefault){try{usingvarconnectionnewSqlConnection(_connectionString);awaitconnection.OpenAsync(cancellationToken);varcommandconnection.CreateCommand();command.CommandTextSELECT 1;awaitcommand.ExecuteScalarAsync(cancellationToken);returnHealthCheckResult.Healthy(数据库连接正常);}catch(Exceptionex){returnHealthCheckResult.Unhealthy(数据库连接失败,exception:ex);}}}常用内置健康检查
数据库健康检查// 添加 NuGet 包AspNetCore.HealthChecks.SqlServerservices.AddHealthChecks().AddSqlServer(connectionString:Configuration.GetConnectionString(DefaultConnection),name:SQL Server,failureStatus:HealthStatus.Unhealthy,tags:new[]{database,sql});
URL 健康检查// 添加 NuGet 包AspNetCore.HealthChecks.Urisservices.AddHealthChecks().AddUrlGroup(uri:newUri(https://api.example.com/health),name:外部API,failureStatus:HealthStatus.Degraded);
内存检查services.AddHealthChecks().AddPrivateMemoryHealthCheck(maximumMegabytes:1024,// 最大内存限制 1GBname:内存使用量);高级配置选项
分组和过滤app.UseEndpoints(endpoints{// 基本健康检查仅包含标记为ready的检查endpoints.MapHealthChecks(/health/ready,newHealthCheckOptions{Predicate(check)check.Tags.Contains(ready)});// 详细健康检查所有检查endpoints.MapHealthChecks(/health/live,newHealthCheckOptions{Predicate(_)true});});
自定义响应格式privatestaticTaskWriteResponse(HttpContextcontext,HealthReportresult){context.Response.ContentTypeapplication/json;varresponsenew{statusresult.Status.ToString(),totalDurationresult.TotalDuration.TotalSeconds.ToString(0:
0.
,checksresult.Entries.Select(enew{namee.Key,statuse.Value.Status.ToString(),duratione.Value.Duration.TotalSeconds.ToString(0:
0.
,descriptione.Value.Description,exceptione.Value.Exception?.Message,datae.Value.Data})};returncontext.Response.WriteAsync(JsonSerializer.Serialize(response));}
延迟启动和超时设置services.AddHealthChecks().AddCheckStartupHealthCheck(启动检查,failureStatus:HealthStatus.Degraded,tags:new[]{ready},timeout:TimeSpan.FromSeconds(
);Kubernetes 集成示例
Pod 配置apiVersion:v1kind:Podmetadata:name:aspnetcore-appspec:containers:-name:appimage:myapp:latestports:-containerPort:80livenessProbe:httpGet:path:/health/liveport:80initialDelaySeconds:10periodSeconds:5readinessProbe:httpGet:path:/health/readyport:80initialDelaySeconds:5periodSeconds:
应用程序配置// 启动时检查services.AddHealthChecks().AddCheckStartupProbe(启动探针,tags:new[]{startup});// 存活检查services.AddHealthChecks().AddCheckLivenessProbe(存活探针,tags:new[]{live});// 就绪检查services.AddHealthChecks().AddCheckReadinessProbe(就绪探针,tags:new[]{ready}).AddCheckDatabaseHealthCheck(数据库,tags:new[]{ready});健康检查 UI
安装包dotnetaddpackage AspNetCore.HealthChecks.UI dotnetaddpackage AspNetCore.HealthChecks.UI.Client dotnetaddpackage AspNetCore.HealthChecks.UI.InMemory.Storage
配置publicvoidConfigureServices(IServiceCollectionservices){services.AddHealthChecks().AddSqlServer(connectionString).AddRedis(redisConnectionString);services.AddHealthChecksUI(settings{settings.AddHealthCheckEndpoint(API,/health);settings.SetEvaluationTimeInSeconds(
;// 每30秒检查一次settings.SetApiMaxActiveRequests(
;// 同时只允许一个请求}).AddInMemoryStorage();}publicvoidConfigure(IApplicationBuilderapp){app.UseRouting();app.UseEndpoints(endpoints{endpoints.MapHealthChecks(/health,newHealthCheckOptions{Predicate_true,ResponseWriterUIResponseWriter.WriteHealthCheckUIResponse});endpoints.MapHealthChecksUI();});}最佳实践
分离检查类型// 存活检查应用是否在运行endpoints.MapHealthChecks(/health/live,newHealthCheckOptions{Predicate_false// 通常很轻量甚至可以是空的});// 就绪检查应用是否准备好处理请求endpoints.MapHealthChecks(/health/ready,newHealthCheckOptions{Predicatecheckcheck.Tags.Contains(ready)});// 启动检查应用是否完成初始化endpoints.MapHealthChecks(/health/startup,newHealthCheckOptions{Predicatecheckcheck.Tags.Contains(startup)});
设置适当的超时services.AddHealthChecks().AddUrlGroup(newUri(http://external-service),external_service,timeout:TimeSpan.FromSeconds(
);// 快速失败
避免昂贵的操作publicclassLightweightHealthCheck:IHealthCheck{publicTaskHealthCheckResultCheckHealthAsync(HealthCheckContextcontext,CancellationTokencancellationToken){// 避免复杂的数据库查询或外部API调用// 使用缓存结果或简单的ping操作returnTask.FromResult(HealthCheckResult.Healthy());}}
安全性考虑app.UseEndpoints(endpoints{endpoints.MapHealthChecks(/health,newHealthCheckOptions{ResponseWriterWriteResponse}).RequireAuthorization();// 需要认证// 或者为监控系统提供公开端点endpoints.MapHealthChecks(/health/public);});监控和警报
集成 Prometheus// 添加包AspNetCore.HealthChecks.Prometheus.Metricsservices.AddHealthChecks().AddPrometheusGatewayPublisher(http://prometheus:9091,health_metrics,optsopts.ReportIntervalSeconds
;
集成 Application Insightsservices.AddHealthChecks().AddApplicationInsightsPublisher(saveDetailedReport:true,instrumentationKey:Configuration[ApplicationInsights:InstrumentationKey]);示例完整配置// Program.csvarbuilderWebApplication.CreateBuilder(args);// 添加健康检查服务builder.Services.AddHealthChecks().AddCheckDatabaseHealthCheck(database,tags:new[]{ready,live}).AddCheckRedisHealthCheck(cache,tags:new[]{ready}).AddCheckStartupHealthCheck(startup,tags:new[]{startup}).AddUrlGroup(newUri(https://payment.api),payment_api,tags:new[]{ready}).AddDiskStorageHealthCheck(ss.AddDrive(C:\\,
)// 磁盘空间检查.AddProcessHealthCheck(sqlservr,pp.Length
;// 进程检查// 配置健康检查UIbuilder.Services.AddHealthChecksUI(setup{setup.AddHealthCheckEndpoint(基本检查,/health);setup.AddHealthCheckEndpoint(就绪检查,/health/ready);setup.AddHealthCheckEndpoint(存活检查,/health/live);}).AddInMemoryStorage();varappbuilder.Build();// 配置端点app.MapHealthChecks(/health);app.MapHealthChecks(/health/ready,newHealthCheckOptions{Predicaterr.Tags.Contains(ready)});app.MapHealthChecks(/health/live,newHealthCheckOptions{Predicaterr.Tags.Contains(live),ResponseWriterWriteMinimalResponse});app.MapHealthChecksUI();app.Run();// 最小化响应staticTaskWriteMinimalResponse(HttpContextcontext,HealthReportreport){context.Response.ContentTypeapplication/json;returncontext.Response.WriteAsync($);}
总结健康检查端点是现代微服务架构中的重要组件它提高可用性通过快速发现并处理故障支持自动恢复容器编排系统可以根据健康检查自动重启服务提供监控数据为运维团队提供应用程序健康状况的实时视图支持渐进式部署确保新版本完全就绪后再接收流量通过合理配置健康检查端点可以显著提高系统的可靠性和可维护性。
9·1免费版nba-9·1免费版应用