ASP.NET Core优雅的添加HealthCheck

ASP.NET Core 2.2 之后提供了内置的 Health Checks 来帮助您监视和报告应用程序的健康状况。默认情况是不需要在额外的引入其它nuget包的,因为AspNet Core自带了这些功能。

public void ConfigureServices(IServiceCollection services)
{
    //使用该扩展方法
    services.AddHealthChecks();
}

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        //使用该扩展方法
        endpoints.MapHealthChecks("/health");
    });
}

进行请求"health"路径,就会得到下面的结果:
image

内置的AddHealthChecks功能比较简单,而现实场景我们是需要对各种指标进行检查的,redis,数据库,RabbitMQ,上游api等等。

而Nugget早已经有人造好轮子,大部分场景我们下载使用即可。

我们可以先添加AspNetCore.Diagnostics.HealthChecks基础包,然后需要添加那种检查,就添加对应的包即可。

<PackageReference Include="AspNetCore.HealthChecks.NpgSql" Version="5.0.2" />
<PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="5.0.1" />
<PackageReference Include="AspNetCore.HealthChecks.Redis" Version="5.0.1" />
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.17" />
services.AddHealthChecks()
	.AddNpgSql("ConnectionString")
	.AddRedis("ConnectionString")
	.AddRabbitMQ("ConnectionString", null, "rabbitMQ");
app.UseEndpoints(endpoints =>
{
	endpoints.MapControllers();
	//设置健康检查终结点
	endpoints.MapHealthChecks("/health", new HealthCheckOptions()
	{
		//设置返回格式
		ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
	});
});

接下来我们再次进行请求"health"路径,就会得到下面的结果:
image

如果还想给健康检查配置访问控制可以
image
一般情况nuget包是够用的

Install-Package AspNetCore.HealthChecks.ApplicationStatus
Install-Package AspNetCore.HealthChecks.ArangoDb
Install-Package AspNetCore.HealthChecks.Aws.S3
Install-Package AspNetCore.HealthChecks.Aws.SecretsManager
Install-Package AspNetCore.HealthChecks.Aws.Sns
Install-Package AspNetCore.HealthChecks.Aws.Sqs
Install-Package AspNetCore.HealthChecks.Aws.SystemsManager
Install-Package AspNetCore.HealthChecks.Azure.IoTHub
Install-Package AspNetCore.HealthChecks.AzureDigitalTwin
Install-Package AspNetCore.HealthChecks.AzureKeyVault
Install-Package AspNetCore.HealthChecks.AzureServiceBus
Install-Package AspNetCore.HealthChecks.AzureStorage
Install-Package AspNetCore.HealthChecks.Consul
Install-Package AspNetCore.HealthChecks.CosmosDb
Install-Package AspNetCore.HealthChecks.DocumentDb
Install-Package AspNetCore.HealthChecks.DynamoDB
Install-Package AspNetCore.HealthChecks.Elasticsearch
Install-Package AspNetCore.HealthChecks.EventStore
Install-Package AspNetCore.HealthChecks.EventStore.gRPC
Install-Package AspNetCore.HealthChecks.Gcp.CloudFirestore
Install-Package AspNetCore.HealthChecks.Gremlin
Install-Package AspNetCore.HealthChecks.Hangfire
Install-Package AspNetCore.HealthChecks.IbmMQ
Install-Package AspNetCore.HealthChecks.InfluxDB
Install-Package AspNetCore.HealthChecks.Kafka
Install-Package AspNetCore.HealthChecks.Kubernetes
Install-Package AspNetCore.HealthChecks.MongoDb
Install-Package AspNetCore.HealthChecks.MySql
Install-Package AspNetCore.HealthChecks.Nats
Install-Package AspNetCore.HealthChecks.Network
Install-Package AspNetCore.HealthChecks.Npgsql
Install-Package AspNetCore.HealthChecks.OpenIdConnectServer
Install-Package AspNetCore.HealthChecks.Oracle
Install-Package AspNetCore.HealthChecks.RabbitMQ
Install-Package AspNetCore.HealthChecks.RavenDB
Install-Package AspNetCore.HealthChecks.Redis
Install-Package AspNetCore.HealthChecks.SendGrid
Install-Package AspNetCore.HealthChecks.SignalR
Install-Package AspNetCore.HealthChecks.Solr
Install-Package AspNetCore.HealthChecks.SqLite
Install-Package AspNetCore.HealthChecks.SqlServer
Install-Package AspNetCore.HealthChecks.System
Install-Package AspNetCore.HealthChecks.Uris

如果nuget没有符合你的包,可以自己实现

public class DatabaseHeaCheakCheck : IHealthCheck
{
	public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
		, CancellationToken cancellationToken = default)
	{
		try
		{
			// 你要检查的业务
			throw new ArgumentNullException();
			return HealthCheckResult.Healthy();
		}
		catch(Exception ex)
		{
			return HealthCheckResult.Unhealthy(exception:ex );
		}
	}
}
services.AddHealthChecks()
	.AddCheck<DatabaseHeaCheakCheck>("Database")
	.AddNpgSql("ConnectionString")
	.AddRedis("ConnectionString")
	.AddRabbitMQ("ConnectionString", null, "rabbitMQ");

接下来我们再次进行请求"health"路径,就会得到下面的结果:
image
微软官方文档-ASP.NET Core 中的运行状况检查
https://learn.microsoft.com/zh-cn/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1#health-check-publisher

posted @ 2023-06-02 23:21  广州大雄  阅读(724)  评论(0编辑  收藏  举报