首页 > 编程语言 >在http://ASP.NET Core中实现健康检查

在http://ASP.NET Core中实现健康检查

时间:2023-03-21 19:36:43浏览次数:56  
标签:Core ASP http httpClientFactory healthCheckService health services 健康检查 public

要实现运行状况检查,您需要在项目中安装 Microsoft.AspNetCore.Diagnostics.HealthChecks 。

接下来,在ConfigureServices方法中添加运行状况检查中间件。

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks();
    services.AddControllers();
}

然后修改Configure方法,使用中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapHealthChecks("/health");
    });
}

现在,准备工作完成,运行程序然后访问 /health, 您将看到下边结果:

 

 

HealthCheckService

.NET Core提供了一个HealthCheckService类,我们可以把健康检查的放到我们的控制器中,就像这样:

public class HealthController : ControllerBase
{
    private readonly ILogger<HealthController> _logger;
    private readonly HealthCheckService _healthCheckService;
    public HealthController(ILogger<HealthController> logger,
        HealthCheckService healthCheckService)
    {
        _healthCheckService = healthCheckService;
        _logger = logger;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var report = await _healthCheckService.CheckHealthAsync();

        return report.Status == HealthStatus.Healthy ? Ok(report) :
            StatusCode((int)HttpStatusCode.ServiceUnavailable, report);
    }
}

现在,如果您尝试访问/health,您将看到相同的结果。

接下来,我们将实现数据库运行状态检查:

EntityFramework Core 健康检查

首先,还是需要安装Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore到我们的项目中。

接下来,我们拿到数据库上下文,然后修改代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddApiVersioning();
}

然后,运行程序,现在访问 /health 返回的结果是这样:

 

 

IHealthCheck

一些情况下,默认的健康检查可能不满足我们的需求,那么可以继承 IHealthCheck 接口,自定义我们的健康检查的逻辑。

public class ApiHealthCheck : IHealthCheck
{
    private readonly IHttpClientFactory _httpClientFactory;

    public ApiHealthCheck(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        using (var httpClient = _httpClientFactory.CreateClient())
        {
            var response = await httpClient.GetAsync("https://your-api-service.endpoint");
            if (response.IsSuccessStatusCode)
            {
                return HealthCheckResult.Healthy($"API is running.");
            }

            return HealthCheckResult.Unhealthy("API is not running");
        }
    }
}

然后修改代码如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddDbContextCheck<WeatherForecastDbContext>()
        .AddCheck<ApiHealthCheck>("ApiHealth");
    services.AddControllers();
}

然后,运行程序,访问 /health,结果如下:

 

 

原文作者: Anuraj
原文链接: https://dotnetthoughts.net/implementing-health-check-aspnetcore/

最后

欢迎扫码关注我们的公众号 【全球技术精选】,专注国外优秀博客的翻译和开源项目分享,也可以添加QQ群 897216102

 

 转 https://zhuanlan.zhihu.com/p/346710313

标签:Core,ASP,http,httpClientFactory,healthCheckService,health,services,健康检查,public
From: https://www.cnblogs.com/wl-blog/p/17241148.html

相关文章