.Net Core基礎的健康檢查

她微笑的臉發表於2020-06-17

前言

健康檢查能檢視我們的應用程式當前是否是一個健康的執行狀態。微軟已經給我們提供了健康檢查輪子,只需要簡單的配置就能完成服務的狀態檢查。一起來實現一個最簡單的健康檢查吧。

開始

  • 新建一個空的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

參考文章

總結

實現了一個最簡單的健康檢查功能,可以在這個基礎上進行自定義的擴充套件和開發。

相關文章