.Net Core基础的健康检查

前言

健康检查能查看我们的应用程序当前是否是一个健康的运行状态。微软已经给我们提供了健康检查轮子,只需要简单的配置就能完成服务的状态检查。一起来实现一个最简单的健康检查吧。

开始

  • 新建一个空的webApi项目。 并引用Microsoft.Extensions.Diagnostics.HealthChecks 包。并在ConfigureServicesConfigure中加入相关配置
public void ConfigureServices(IServiceCollection services)
{
    //健康检查服务
    services.AddHealthChecks();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //加入中间件
    app.UseHealthChecks("/healthChecks");
}

最简单的检查就完成了,我们测试一下。
图片名称

返Healthy,表示服务正常。

自定义拓展

HealthChecks提供了一个IHealthCheck接口,这个接口只有一个CheckHealthAsync方法,我们只需要实现这个接口就可以实现我们需要的各种自定义的检查项目。CheckHealthAsync返回一个HealthCheckResult的枚举代表健康检查的几种状态,分别是异常,降级,健康。

public enum HealthStatus
{
    Unhealthy = 0,
    Degraded = 1,
    Healthy = 2,
}

实现接口,返回不健康状态。

public class SqlHealthChecks : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
    {
        if (1 == 1)
        {
            return Task.FromResult(HealthCheckResult.Unhealthy());
        }
    }
}

ConfigureServices中添加自定义的检查,AddCheck可以添加你自定的健康检查服务,

public void ConfigureServices(IServiceCollection services)
{
    //健康检查服务
    services.AddHealthChecks().AddCheck<SqlHealthChecks>("key");
}

测试可以发现返回的为不健康的应用
图片名称

自定义返回值

我们可以利用HealthCheckOptions来实现健康检查的自定义返回内容.

private static Task WriteResponse(HttpContext context, HealthReport healthReport)
{
    context.Response.ContentType = "application/json";
    var result = JsonHelper.SerializeObject(new
    {
        code = context.Response.StatusCode,
        errors = healthReport.Entries.Select(e => new
        {
            key = e.Key,
            value = e.Value.Status.ToString()
        })
    });

    return context.Response.WriteAsync(result);
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
{

    app.UseHealthChecks("/healthChecks", new HealthCheckOptions{ResponseWriter = WriteResponse});

}

测试返回效果

图片名称

引入Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore 可以为DbContext进行检查


public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks().AddCheck<SqlHealthChecks>("key").AddDbContextCheck<DbContext>("DbContext");
}

健康检查UI

引入AspNetCore.HealthChecks.UI并在ConfigureServicesConfigure中加入相应的配置

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddHealthChecksUI();  
}  

public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
{  
    app.UseHealthChecksUI();  
}  

appsetting,json文件中加入配置

{
  "HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "HealthCheck",
        "Uri": "https://localhost:5000/healthCheck"
      }
    ],
    "EvaluationTimeinSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }
}

启动项目并指向/healthchecks-ui。

扩展包

开源社区已经有很多现有的优秀的扩展包我们可以直接引用

AspNetCore.HealthChecks.Npgsql
AspNetCore.HealthChecks.Redis
AspNetCore.HealthChecks.AzureStorage
AspNetCore.HealthChecks.AzureServiceBus
AspNetCore.HealthChecks.MySql
AspNetCore.HealthChecks.DocumentDb
AspNetCore.HealthChecks.SqLite
AspNetCore.HealthChecks.Kafka
AspNetCore.HealthChecks.RabbitMQ
AspNetCore.HealthChecks.IdSvr
AspNetCore.HealthChecks.DynamoDB
AspNetCore.HealthChecks.Oracle
AspNetCore.HealthChecks.Uris
AspNetCore.HealthChecks.System
AspNetCore.HealthChecks.Network
AspNetCore.HealthChecks.SqlServer
AspNetCore.HealthChecks.MongoDb

参考文章

总结

实现了一个最简单的健康检查功能,可以在这个基础上进行自定义的扩展和开发。

posted @ 2020-06-17 10:51  她微笑的脸  阅读(3342)  评论(10编辑  收藏  举报