.NET Core中提供了開箱即用的運行情況檢查,首先,我將在.NET Core API應用程序中執行運行情況檢查,接下來,咱們將使用DbContext集成SQL Server或數據庫的運行情況檢查,最後是如何實現自定義服務的運行情況檢查。數據庫
要實現運行情況檢查,您須要在項目中安裝 Microsoft.AspNetCore.Diagnostics.HealthChecks
。api
接下來,在ConfigureServices
方法中添加運行情況檢查中間件。app
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); services.AddControllers(); }
而後修改Configure
方法,使用中間件:async
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); }); }
如今,準備工做完成,運行程序而後訪問 /health, 您將看到下邊結果:ui
.NET Core提供了一個HealthCheckService類,咱們能夠把健康檢查的放到咱們的控制器中,就像這樣:.net
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,您將看到相同的結果。3d
接下來,咱們將實現數據庫運行狀態檢查:code
首先,仍是須要安裝Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore
到咱們的項目中。中間件
接下來,咱們拿到數據庫上下文,而後修改代碼:blog
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddApiVersioning(); }
而後,運行程序,如今訪問 /health 返回的結果是這樣:
一些狀況下,默認的健康檢查可能不知足咱們的需求,那麼能夠繼承 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/