.NET Core 中实现健康检查
前言
.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");
});
}
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();
}
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();
}
- EOF -
推荐阅读 点击标题