gpt4 book ai didi

c# - 在 .NET Core Worker Service 中执行健康检查

转载 作者:行者123 更新时间:2023-12-01 19:07:24 25 4
gpt4 key购买 nike

如何在 .NET Core Worker Service 中实现运行状况检查?

该服务将在 Docker 内部运行,并且需要能够检查服务的运行状况。

最佳答案

执行此操作的另一种方法是实现 IHealthCheckPublisher

这种方法的好处是能够重用现有的 IHealthCheck 或与依赖 IHealthCheck 接口(interface)的第三方库集成(例如 this one ) .

虽然您仍然将 Microsoft.NET.Sdk.Web 作为 SDK,但您不需要添加任何 ASP.NET 细节。

这是一个例子:

public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host
.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services
.AddHealthChecks()
.AddCheck<RedisHealthCheck>("redis_health_check")
.AddCheck<RfaHealthCheck>("rfa_health_check");

services.AddSingleton<IHealthCheckPublisher, HealthCheckPublisher>();
services.Configure<HealthCheckPublisherOptions>(options =>
{
options.Delay = TimeSpan.FromSeconds(5);
options.Period = TimeSpan.FromSeconds(5);
});
});
}

public class HealthCheckPublisher : IHealthCheckPublisher
{
private readonly string _fileName;
private HealthStatus _prevStatus = HealthStatus.Unhealthy;

public HealthCheckPublisher()
{
_fileName = Environment.GetEnvironmentVariable(EnvVariableNames.DOCKER_HEALTHCHECK_FILEPATH) ??
Path.GetTempFileName();
}

public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
{
// AWS will check if the file exists inside of the container with the command
// test -f $DOCKER_HEALTH_CHECK_FILEPATH

var fileExists = _prevStatus == HealthStatus.Healthy;

if (report.Status == HealthStatus.Healthy)
{
if (!fileExists)
{
using var _ = File.Create(_fileName);
}
}
else if (fileExists)
{
File.Delete(_fileName);
}

_prevStatus = report.Status;

return Task.CompletedTask;
}
}

关于c# - 在 .NET Core Worker Service 中执行健康检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58770795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com