程序员开发程序,是“”的过程,运维人员负责日常运维,是“”的过程,在养的过程,运维人员希望在第一时间了解程序的状况,健康检查,是最基础的手段。

var builder = WebApplication.CreateBuilder(args);
//注入健康检查服务
builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapGet("/test", () =>
{ return DateTime.Now;
});
//添加中间件,设置健康检查的访问路径是/health
app.MapHealthChecks("/health");
app.Run();

.NET6之MiniAPI(十三):健康检查_sed

 

 

   还可以通过重写来改变返回的字符串:

app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = (context, result) =>
{
var backContent = "this is health";
return context.Response.WriteAsync(backContent);
}
});

  当然,这样的健康检查只是host有没有启动,如果有更深层次的检查,可以通过实现IHealthCheck来实现。

using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);
//注入自定义健康检查类
builder.Services.AddHealthChecks()
.AddCheck<TestHealthCheck>("test_health_check");
var app = builder.Build();
app.MapGet("/test", () =>
{
return DateTime.Now;
});
//添加中间件,设置健康检查的访问路径是/health
app.MapHealthChecks("/health");
app.Run();

public class TestHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
//这是一个三方的获取空闲内存的库
var client = new MemoryMetricsClient();
var metrics = client.GetMetrics();
Console.WriteLine("Free : " + metrics.Free);
//假业务要求,内存大于1000M,就健康
var healthCheckResultHealthy = metrics.Free > 1000;
if (healthCheckResultHealthy)
{
return Task.FromResult(
HealthCheckResult.Healthy("healthy"));
}
return Task.FromResult(
new HealthCheckResult(context.Registration.FailureStatus,
"unhealthy"));
}
}

  有了这个实现,就可以很方便地实现业务中的各种判定服务是否健康了。

  上面的所有健康检查都是拉模式,意思就是外部监控服务会请求本服务的/health,获取信息,来判定是否健康,在asp.net core也提供了推的模式,如下:

using Microsoft.Extensions.Diagnostics.HealthChecks;
using MiniDemo05;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks()
.AddCheck<TestHealthCheck>("test_health_check");
//配置推送的参数
builder.Services.Configure<HealthCheckPublisherOptions>(options =>
{
options.Delay = TimeSpan.FromSeconds(1);
options.Period = TimeSpan.FromSeconds(5);
});
//注入推送服务
builder.Services.AddSingleton<IHealthCheckPublisher, HealthPublisher>();

var app = builder.Build();

app.MapGet("/test", () =>
{

return DateTime.Now;
});

app.Run();

public class TestHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var client = new MemoryMetricsClient();
var metrics = client.GetMetrics();
Console.WriteLine("Total: " + metrics.Total);
Console.WriteLine("Used : " + metrics.Used);
Console.WriteLine("Free : " + metrics.Free);

var healthCheckResultHealthy = metrics.Free > 6000;
if (healthCheckResultHealthy)
{
return Task.FromResult(
HealthCheckResult.Healthy("healthy"));
}
return Task.FromResult(
new HealthCheckResult(context.Registration.FailureStatus,
"unhealthy"));
}
}
public class HealthPublisher : IHealthCheckPublisher
{
private readonly ILogger<HealthPublisher> _logger;
public HealthPublisher(ILogger<HealthPublisher> logger)
{
_logger = logger;
}
public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
{
_logger.LogInformation($"{DateTime.Now.ToString()},{ report.Status}");
return Task.CompletedTask;
}
}

  如果监控参数收集是一个url,我们可以在HealthPublisher中把健康的结果推送上去。

  想要更快更方便的了解相关知识,可以关注微信公众号 

.NET6之MiniAPI(十三):健康检查_sed_02