将 .NET Core Generic Host 用于处理异步消息的应用程序。
我们使用通用主机而不是 .NET Core WebHost 的原因是因为我的一位同事曾见过几次 MassTransit(我们正在使用的轻量级服务总线框架)作为 .NET 的一部分运行在 Linux 上,Core WebHost 在收到 SIGTERM 信号后并不总是正常关闭 - 我们必须使用 SIGKILL 来强制终止进程。
该应用程序将在 Kubernetes 上运行,我们希望使用 K8s 活性探针实现自我修复架构。在其他使用 WebHost 的 .NET Core 应用程序中,我们使用了 .NET Core 2.2 中引入的健康检查,但我不知道如何在通用主机中使用这样的中间件。
在 WebHost 中,我可以按如下方式配置中间件:
app.UseHealthChecks(appSettings.HealthChecksPath ?? "/health");
如果使用 .NET Core 通用主机,我将如何执行此操作...
亲切的问候。
通过使用基于 HttpListener 的健康检查服务器解决了这个问题 - 很高兴被证明是错误的,但据我所知,Kestrel / ASP.NET Core 中间件不适合 .NET 2.2 和通用主机。
请参阅此处获取代码。
您不需要创建自定义 http 侦听器。我相信它的意图是这样的: ```` 使用 IHost 主机 = Host.CreateDefaultBuilder(args) .UseSerilog(记录器) .ConfigureServices((_, 服务) => { //配置通用主机服务 } ) .ConfigureWebHostDefaults(webBuilder => { //这是您设置网络服务器的地方 webBuilder.UseKestrel((c, 选项) => { options.ListenAnyIP(config.Healthcheckport,listenoption => { ListenOption.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1AndHttp2; }); }); }) .ConfigureWebHost(aa => { //在这里您指定有关端点映射的更多详细信息 aa.UseStartup(); }) .Build();
```
public class WebHostStartup
{
private readonly AppSettings config;
public WebHostStartup()
{
this.config = new AppSettings().GetSettings(); //your own parsed settings if you need it
}
public void ConfigureServices(IServiceCollection services)
{
//set up services associated with the webserver
services.AddRouting();
services.AddHealthChecks()
.AddTypeActivatedCheck<SqlServerCheck>(nameof(SqlServerCheck)
, failureStatus: HealthStatus.Unhealthy
, tags: new[] { HealthCheckTag.Startup, HealthCheckTag.Ready }
, args: new object[] { config.ConnectionStringToRetrieveDataFrom })
.AddCheck<LivenessCheck>(nameof(LivenessCheck), tags: new[] { HealthCheckTag.Live });
}
public void Configure(IApplicationBuilder app)
{
//Here set up the routing
app.UseWhen(context => context.Connection.LocalPort == config.Healthcheckport,
applicationBuilder =>
{
applicationBuilder.UseRouting();
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
//applicationBuilder.UseAuthentication();
applicationBuilder.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks(HealthCheckEndPoint.All);
endpoints.MapHealthChecks(HealthCheckEndPoint.Startup, new HealthCheckOptions
{
Predicate = healthCheck => healthCheck.Tags.Contains(HealthCheckTag.Startup)
});
endpoints.MapHealthChecks(HealthCheckEndPoint.Ready, new HealthCheckOptions
{
Predicate = healthCheck => healthCheck.Tags.Contains(HealthCheckTag.Ready)
});
endpoints.MapHealthChecks(HealthCheckEndPoint.Live, new HealthCheckOptions
{
Predicate = healthCheck => healthCheck.Tags.Contains(HealthCheckTag.Live)
});
});
});
}
}
```