在这里我们使用匿名方法AddCheck(),来编写我们的自定义的验证逻辑,结果是HealthCheckResult对象,该对象包含3个选项
Healthy 健康 Unhealthy 不良 Degraded 降级option 2
实现IHealthCheck接口并实现CheckHealthAsync()方法,如下所示:
public class DatabaseHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken =
default)
{
using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true"))
{
try
{
connection.Open();
}
catch (SqlException)
{
return Task.FromResult(HealthCheckResult.Unhealthy());
}
}
return Task.FromResult(HealthCheckResult.Healthy());
}
}
创建该类之后,我们需要通过使用一些有效的唯一名称,AddCheck
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("sql");
}
现在我们的代码就写完了,我们可以像上面那样添加任意数量的Health Task,它将按照我们在此处声明的顺序运行。
自定义状态码
在之前我们也说过200为健康,503为不健康那么Healthcheck服务甚至通过以下方式使用其options对象提供自定义状态代码,为我们提供了更改此默认的状态码。
config.MapHealthChecks("/health", new HealthCheckOptions
{
ResultStatusCodes = new Dictionary<HealthStatus, int> { { HealthStatus.Unhealthy, 420 }, { HealthStatus.Healthy, 200 }, { HealthStatus.Degraded, 419 } }
});
自定义输出
我们可以自定义输出,以获取有关每个运行状况检查任务的更清晰详细的信息。如果我们有多个运行状况检查任务来分析哪个任务使整个服务健康状态变为”不正常“,这将非常有用。
我们可以通过HealthCheckOptions ResponseWriter属性来实现。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app
.UseRouting()
.UseEndpoints(config =>
{
config.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter=CustomResponseWriter
});
});
}
private static Task CustomResponseWriter(HttpContext context, HealthReport healthReport)
{
context.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject(new
{
status = healthReport.Status.ToString(),
errors = healthReport.Entries.Select(e => new
{
key = e.Key,
value = e.Value.Status.ToString()
})
});
return context.Response.WriteAsync(result);
}








