.Net Core基礎的健康檢查
阿新 • • 發佈:2020-06-17
## **前言**
健康檢查能檢視我們的應用程式當前是否是一個健康的執行狀態。微軟已經給我們提供了健康檢查輪子,只需要簡單的配置就能完成服務的狀態檢查。一起來實現一個最簡單的健康檢查吧。
## **開始**
* 新建一個空的webApi專案。 並引用`Microsoft.Extensions.Diagnostics.HealthChecks` 包。並在`ConfigureServices`和`Configure`中加入相關配置
``` csharp
public void ConfigureServices(IServiceCollection services)
{
//健康檢查服務
services.AddHealthChecks();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//加入中介軟體
app.UseHealthChecks("/healthChecks");
}
```
最簡單的檢查就完成了,我們測試一下。
返Healthy,表示服務正常。
## **自定義拓展**
HealthChecks提供了一個`IHealthCheck`介面,這個介面只有一個`CheckHealthAsync`方法,我們只需要實現這個介面就可以實現我們需要的各種自定義的檢查專案。`CheckHealthAsync`返回一個`HealthCheckResult`的列舉代表健康檢查的幾種狀態,分別是異常,降級,健康。
``` csharp
public enum HealthStatus
{
Unhealthy = 0,
Degraded = 1,
Healthy = 2,
}
```
實現介面,返回不健康狀態。
```csharp
public class SqlHealthChecks : IHealthCheck
{
public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
{
if (1 == 1)
{
return Task.FromResult(HealthCheckResult.Unhealthy());
}
}
}
```
為`ConfigureServices`中新增自定義的檢查,`AddCheck`可以新增你自定的健康檢查服務,
``` csharp
public void ConfigureServices(IServiceCollection services)
{
//健康檢查服務
services.AddHealthChecks().AddCheck("key");
}
```
測試可以發現返回的為不健康的應用
#### **自定義返回值**
我們可以利用`HealthCheckOptions`來實現健康檢查的自定義返回內容.
```csharp
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);
}
```
``` csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
{
app.UseHealthChecks("/healthChecks", new HealthCheckOptions{ResponseWriter = WriteResponse});
}
```
測試返回效果
引入`Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore` 可以為DbContext進行檢查
``` csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks().AddCheck("key").AddDbContextCheck("DbContext");
}
```
## **健康檢查UI**
引入`AspNetCore.HealthChecks.UI`並在`ConfigureServices`和`Configure`中加入相應的配置
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecksUI();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHealthChecksUI();
}
```
在`appsetting,json`檔案中加入配置
``` json
{
"HealthChecksUI": {
"HealthChecks": [
{
"Name": "HealthCheck",
"Uri": "https://localhost:5000/healthCheck"
}
],
"EvaluationTimeinSeconds": 10,
"MinimumSecondsBetweenFailureNotifications": 60
}
}
```
啟動專案並指向/healthchecks-ui。
## **擴充套件包**
開源社群已經有很多現有的優秀的擴充套件包我們可以直接引用
``` java
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
```
## **參考文章**
* [ 微軟官方文件 ](https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1#entity-framework-core-dbcontext-probe)
* [ 社群 ](https://www.c-sharpcorner.com/article/implementing-net-core-health-checks/)
* [ 原始碼理解HealthCheck ](https://www.cnblogs.com/edison0621/p/11968102.html)
## **總結**
實現了一個最簡單的健康檢查功能,可以在這個基礎上進行自定義的擴充套件和開發。