.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/