在.NET Core 中实现健康检查
.NET Core中提供了開箱即用的運行狀況檢查,首先,我將在.NET Core API應用程序中執(zhí)行運行狀況檢查,接下來,我們將使用DbContext集成SQL Server或數(shù)據(jù)庫的運行狀況檢查,最后是如何實現(xiàn)自定義服務的運行狀況檢查。
在ASP.NET Core中實現(xiàn)健康檢查
要實現(xiàn)運行狀況檢查,您需要在項目中安裝?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");}); }現(xiàn)在,準備工作完成,運行程序然后訪問 /health, 您將看到下邊結(jié)果:
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);} }現(xiàn)在,如果您嘗試訪問/health,您將看到相同的結(jié)果。
接下來,我們將實現(xiàn)數(shù)據(jù)庫運行狀態(tài)檢查:
EntityFramework Core 健康檢查
首先,還是需要安裝Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore到我們的項目中。
接下來,我們拿到數(shù)據(jù)庫上下文,然后修改代碼:
public void ConfigureServices(IServiceCollection services) {services.AddControllers();services.AddApiVersioning(); }然后,運行程序,現(xiàn)在訪問 /health 返回的結(jié)果是這樣:
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,結(jié)果如下:
原文作者: Anuraj 原文鏈接:?https://dotnetthoughts.net/implementing-health-check-aspnetcore/[1]
最后
歡迎掃碼關(guān)注我們的公眾號 【全球技術(shù)精選】,專注國外優(yōu)秀博客的翻譯和開源項目分享,也可以添加QQ群 897216102
References
[1]?https://dotnetthoughts.net/implementing-health-check-aspnetcore/:?"https://dotnetthoughts.net/implementing-health-check-aspnetcore/"
總結(jié)
以上是生活随笔為你收集整理的在.NET Core 中实现健康检查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聊聊如何构建一支自驱团队(一)
- 下一篇: 领域驱动设计-从贫血模型到充血模型