4

I am working with microservice (multiple services) and want to have HealthCheck service which I can call and get health of all the running service. I wan't to trigger healthcheck for each of the service. The idea is to get health of each service via GRPC.

One of my service has :

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

How can I run health check through code when my GRPC endpoint is called in this service and get result.

hbe
  • 43
  • 5
  • gRPC has a health check interface that you can implement on all your services. You would still need something to call it though. https://github.com/grpc/grpc/blob/master/doc/health-checking.md – Rob Goodwin May 21 '20 at 14:13
  • Sorry if my question is not clear (first time on stackoverflow). I am not trying to do a healthcheck of gRPC but I am trying to use gRPC to do a healthcheck of other services as well (like database). I am able to connect gRPC all together (send and receive is working fine) but I want to know the best way to query the default "healthcheck" pipleline (Which we get from app.UseHealthChecks("/health");). – hbe May 29 '20 at 08:50

1 Answers1

5

When services.AddHealthChecks() is invoked, an instance of Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckService is added to the container. You can access this instance using dependency injection and call CheckHealthAsync to generate a health report which will use the registered health checks.

In my project I needed to execute the health check, when a MassTransit event is received:

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
    }
}
Thomas Hetzer
  • 1,537
  • 13
  • 24