通过aspnet core中的代码触发HealthCheck

hbe*_*hbe 4 asp.net-core grpc-dotnet health-check

我正在使用微服务(多个服务),并且希望拥有 HealthCheck 服务,我可以调用该服务并获取所有正在运行的服务的运行状况。我不想触发每项服务的运行状况检查。这个想法是通过 GRPC 获取每个服务的健康状况。

我的一项服务有:

''' services.AddHealthChecks() .AddCheck("Ping", () => HealthCheckResult.Healthy("Ping 正常!"), Tags: new[] { "ping_tag" }).AddDbContextCheck(name: "我的数据库”);'''

当在此服务中调用我的 GRPC 端点并获取结果时,如何通过代码运行运行状况检查。

小智 5

调用时services.AddHealthChecks(),会将 的实例Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService添加到容器中。您可以使用依赖项注入访问此实例,并调用CheckHealthAsync生成运行状况报告,该报告将使用注册的运行状况检查。

在我的项目中,当收到 MassTransit 事件时,我需要执行运行状况检查:

public class HealthCheckQueryEventConsumer : IConsumer<IHealthCheckQueryEvent>
{
    private readonly HealthCheckService myHealthCheckService;   
    public HealthCheckQueryEventConsumer(HealthCheckService healthCheckService)
    {
        myHealthCheckService = healthCheckService;
    }

    public async Task Consume(ConsumeContext<IHealthCheckQueryEvent> context)
    {
        HealthReport report = await myHealthCheckService.CheckHealthAsync();
        string response = JsonSerializer.Serialize(report);
        // Send response
    }
}
Run Code Online (Sandbox Code Playgroud)