前言
ASP.NET Core提供运行状况检查Middleware和库,以便于报告应用的运行状况。
使用方式也很简单。
引用Nuget包Microsoft.Extensions.Diagnostics.HealthChecks
。
然后修改Startup.cs文件:
public void ConfigureServices(IServiceCollection services)
{...services.AddHealthChecks();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{...app.UseHealthChecks("/health");
}
我们甚至可以为第三方组件,比如数据库、缓存,提供健康状态检查。
最后,访问/health
来查看应用程序的健康状态:
这种文本方式不够直观,今天我们介绍一个轻量级的图形UI,通过可视化的方式进行健康检查。
Demo
1.引用Nuget包
引用如下Nuget包:
AspNetCore.HealthChecks.UI
AspNetCore.HealthChecks.UI.Client
AspNetCore.HealthChecks.UI.InMemory.Storage
UI支持不同的存储类型,如Sql Server、MySql等,这里选择直接保存到内存。
2.修改Startup.cs
添加UI,并设置了自定义健康检查,用于演示不健康状态:
public void ConfigureServices(IServiceCollection services)
{...services.AddHealthChecksUI().AddInMemoryStorage();services.AddHealthChecks().AddCheck<DemoHealthCheck>("My IO");
}public class DemoHealthCheck: IHealthCheck
{public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default){if (DateTime.Now.Second > 30){return Task.FromResult(HealthCheckResult.Healthy());}return Task.FromResult(HealthCheckResult.Unhealthy("不健康"));}
}
指定健康检查和UI的地址,并且使用UIResponseWriter.WriteHealthCheckUIResponse
返回json格式健康检查数据:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{...app.UseEndpoints(endpoints =>{endpoints.MapControllers();endpoints.MapHealthChecks("/health", new HealthCheckOptions(){Predicate = _ => true,ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse});endpoints.MapHealthChecksUI(options => options.UIPath = "/health-ui");});
}
3.添加配置项
修改appsettings.json文件:
"HealthChecksUI": {"HealthChecks": [{"Name": "My IO","Uri": "/health"}],"Webhooks": [{"Name": "","Uri": "","Payload": "","RestoredPayload": ""}],"EvaluationTimeinSeconds": 10,"MinimumSecondsBetweenFailureNotifications": 60}
HealthChecks
是个数组,也就是说,UI同时可以监控多个健康检查API。
Webhooks
用于当API的健康状态改变时,向指定Uri发送告警数据。
4.使用
运行程序,访问/health-ui
即可打开UI:
点击Details
按钮,还可查看健康状态历史: