在 asp net core 中通过代码触发健康检查

Trigger HealthCheck by code in aspnet core

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

我的一项服务有:

''' services.AddHealthChecks() .AddCheck("Ping", () => HealthCheckResult.Healthy("Ping is OK!"), 标签: new[] { "ping_tag" }).AddDbContextCheck(name: "My DB") ; '''

当我的 GRPC 端点在此服务中被调用并获得结果时,我如何 运行 通过代码进行健康检查。

当调用 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
    }
}