在.NET Core 中實現健康檢查
阿新 • • 發佈:2021-01-25
.NET Core中提供了開箱即用的執行狀況檢查,首先,我將在.NET Core API應用程式中執行執行狀況檢查,接下來,我們將使用DbContext整合SQL Server或資料庫的執行狀況檢查,最後是如何實現自定義服務的執行狀況檢查。
![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210124_095355.png)
## 在ASP.NET Core中實現健康檢查
要實現執行狀況檢查,您需要在專案中安裝 `Microsoft.AspNetCore.Diagnostics.HealthChecks` 。
接下來,在`ConfigureServices`方法中新增執行狀況檢查中介軟體。
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
services.AddControllers();
}
```
然後修改`Configure`方法,使用中介軟體:
```csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
}
```
現在,準備工作完成,執行程式然後訪問 /health, 您將看到下邊結果:
![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210124_093839.png)
## HealthCheckService
.NET Core提供了一個HealthCheckService類,我們可以把健康檢查的放到我們的控制器中,就像這樣:
```csharp
public class HealthController : ControllerBase
{
private readonly ILogger _logger;
private readonly HealthCheckService _healthCheckService;
public HealthController(ILogger logger,
HealthCheckService healthCheckService)
{
_healthCheckService = healthCheckService;
_logger = logger;
}
[HttpGet]
public async Task 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`到我們的專案中。
接下來,我們拿到資料庫上下文,然後修改程式碼:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApiVersioning();
}
```
然後,執行程式,現在訪問 /health 返回的結果是這樣:
![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210124_094517.png)
## IHealthCheck
一些情況下,預設的健康檢查可能不滿足我們的需求,那麼可以繼承 IHealthCheck 介面,自定義我們的健康檢查的邏輯。
```csharp
public class ApiHealthCheck : IHealthCheck
{
private readonly IHttpClientFactory _httpClientFactory;
public ApiHealthCheck(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task 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");
}
}
}
```
然後修改程式碼如下:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddDbContextCheck()
.AddCheck("ApiHealth");
services.AddControllers();
}
```
然後,執行程式,訪問 /health,結果如下:
![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210124_094946.png)
> 原文作者: Anuraj
> 原文連結: [https://dotnetthoughts.net/implementing-health-check-aspnetcore/]("https://dotnetthoughts.net/implementing-health-check-aspnetcore/