zoukankan      html  css  js  c++  java
  • 在.NET Core 中实现健康检查

    .NET Core中提供了开箱即用的运行状况检查,首先,我将在.NET Core API应用程序中执行运行状况检查,接下来,我们将使用DbContext集成SQL Server或数据库的运行状况检查,最后是如何实现自定义服务的运行状况检查。

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

    要实现运行状况检查,您需要在项目中安装 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/

  • 相关阅读:
    TextView控件中使用android:drawableLeft图片和文字使用gravity只能使文字居中,无法使图片随文字同时居中, 让图片随文字同时居中
    Android Studio sdk无法下载的问题
    CollapsingToolbarLayout的使用,实现向上滑动时,图片自动压缩消失,下拉到最上面图片显示出来
    android studio开发app时,运行时百度地图显示合适,app打包后地图不显示
    两个日期相差的天数
    Android实现定点任务(定时定点做某事)
    Conversion to Dalvik format failed: Unable to execute dex: Cannot merge new index 69457 into a non-jumbo instruction!
    JSP易错点及常用标签
    Java异常机制总结
    java内存区域简单介绍
  • 原文地址:https://www.cnblogs.com/myshowtime/p/14322587.html
Copyright © 2011-2022 走看看