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