假设我有一个服务需要在启动时做一些工作。因此,它从“可启动”状态开始,继续进入“正在启动”,然后是“就绪”、“停止”,然后再次进入“可启动”状态。
这些状态映射到 HealthStatuses,如下所示:
状态 | 健康状况 |
---|---|
可启动 | 不健康 |
开始 | 降级 |
准备好 | 健康 |
停止 | 降级 |
当环境执行活性检查时,我希望服务在降级时呈现为活动状态(至少我是这样解释该术语的)。当谈到服务是否准备好提供服务时,只有当 HealthStatus 为 Healthy 时我才会肯定地回答。有没有办法实现这一点,还是我过度解释了 API?
提前非常感谢您的帮助。
可以自定义健康检查输出报告,您只需使用
ResponseWriter
中的HealthCheckOptions
:
app.MapHealthChecks("/healthz", new HealthCheckOptions
{
ResponseWriter = WriteResponse
});
///////
private static async Task WriteResponse(HttpContext context, HealthReport report)
{
context.Response.ContentType = "application/json";
HealthCheckResponse value = new HealthCheckResponse
{
// here you can set Status to whatever you want based on entries status
Status = (report.Entries.Any() && report.Entries.All(x => x.Value.Status == HealthStatus.Degraded) ? HealthStatus.Unhealthy : report.Status).ToString(),
Checks = report.Entries.Select((KeyValuePair<string, HealthReportEntry> x) => new HealthCheck
{
Componenet = x.Key,
Status = x.Value.Status.ToString(),
Description = x.Value.Description,
Duration = x.Value.Duration
}),
Duration = report.TotalDuration
};
if (value.Status == HealthStatus.Unhealthy.ToString())
context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
await context.Response.WriteAsync(JsonSerializer.Serialize(value));
}
有关更多详细信息,请阅读文档:https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-8.0#customize-output