.NET Core 3.x中的多个健康检查端点

6

在.NET Core 3.x中,有没有一种方法可以配置多个健康检查终点?

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
};

这是我目前拥有的,似乎无法在此基础上配置另一个。

在这种情况下,重定向不起作用,因为其中一个端点将位于防火墙后面。

2个回答

14

如果您想要拥有多个健康检查端点,但不确定您的目的是什么。

如果是为了支持不同的“活动状态”和“可读性”健康检查,则正确的方法由Microsoft文档 "Filter Health Checks" 指出。

实质上,它依赖于向您的健康检查添加标签,然后使用这些标签将其路由到适当的控制器。您不需要使用“live”标记指定健康检查,因为您可以直接通过基本的Http测试获得。

在Startup.ConfigureServices()

services.AddHealthChecks()
        .AddCheck("SQLReady", () => HealthCheckResult.Degraded("SQL is degraded!"), tags: new[] { "ready" })
        .AddCheck("CacheReady", () => HealthCheckResult.Healthy("Cache is healthy!"), tags: new[] { "ready" });

在 Startup.Configure() 中

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("ready"),});

    endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = (_) => false});
});

9

由于HealthChecks是一个普通的中间件,因此您可以像配置其他正常中间件一样始终配置管道。

例如:

//in a sequence way
app.UseHealthChecks("/path1");
app.UseHealthChecks("/path2");

// in a branch way: check a predicate function dynamically
app.MapWhen(
    ctx => ctx.Request.Path.StartsWithSegments("/path3") || ctx.Request.Path.StartsWithSegments("/path4"), 
    appBuilder=>{
        appBuilder.UseMiddleware<HealthCheckMiddleware>();
    }
);

// use endpoint routing
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapHealthChecks("/health1");
    endpoints.MapHealthChecks("/health2");
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接