【问题标题】:How to configure HealthCheck with IHost?如何使用 IHost 配置 HealthCheck?
【发布时间】:2023-01-24 22:04:29
【问题描述】:

在我们当前的 healthcheck 工人服务实施中,我们这样做(简化)

var options = new WebApplicationOptions {
    Args = args, 
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() 
        ? AppContext.BaseDirectory 
        : default
};

var builder = WebApplication.CreateBuilder(options);

builder.Host.UseWindowsService();

builder.Services.AddHealthChecks().AddCheck<ServiceIsOnlineCheck>(nameof(ServiceIsOnlineCheck));
builder.Services.AddHostedService<Worker>();

var healthcheckoptions = new HealthCheckOptions
{
    ResponseWriter = ResponseWriters.WriteDetailedStatus,
    ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status200OK,
                [HealthStatus.Unhealthy] = StatusCodes.Status200OK
            }
};

var app = builder.Build();
app.UseHealthChecks("/health", healthcheckoptions);

app.Run();

当我在 .NET 7 中创建一个新的辅助服务时,program.cs 中的设置完全不同,我无法理解我们如何在其中设置健康检查。

program.cs 长这个样子,你怎么实现的? (我们需要设置自己的响应编写器和其他自定义选项)

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "Service Name";
    })
    .ConfigureWebHost(host =>
    {
        // ???
    })
    .ConfigureServices(services =>
    {
        services.AddHostedService<RunOnScheduleWorker>();
    })
    .Build();

host.Run();

【问题讨论】:

    标签: c# health-check .net-7.0 worker-service


    【解决方案1】:

    此模板使用通用托管(在 .NET 6 之前的模板中使用),因此您可以使用 Startup 对其进行设置。这是我使用的小型 sn-p,您可以从中汲取灵感:

    IHost host = Host.CreateDefaultBuilder(args)
        .UseConsoleLifetime()
        .ConfigureWebHostDefaults(builder =>
        {
            builder.UseStartup<Startup>();
        })
        .ConfigureServices(services => { services.AddHostedService<Worker>(); })
        .Build();
    
    
    host.Run();
    
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHealthChecks("/health");
        }
    }
    

    但你不仅限于使用它,你可以:

    • 切换到以前使用的那个,只需从您使用的那个复制粘贴所有内容。
    • 由于您想要公开 ASP.NET Core 端点 - 使用相应的项目类型并向其添加托管服务。

    阅读更多:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2020-10-16
      • 1970-01-01
      • 2020-01-13
      • 2022-12-29
      • 2020-06-14
      • 2019-07-26
      相关资源
      最近更新 更多