如何实现 asp.net core 安全优雅退出
0 条评论我想问一个老生常谈的问题,如何可以保证程序优雅的退出,这里用 优雅 的目的是因为我想在退出之前做一些小动作。
用户场景:希望在程序退出之前可以从 Consul 上解注册, 下面是我的模板代码。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((host, config) =>
{
})
.UseStartup<Service>();
实现:
为了能够让程序优雅的退出,你可以用 IHostApplicationLifetime 哈,它定义了很多 action 枚举,比如:启动前,启动后,停止前 等等
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Allows consumers to be notified of application lifetime events. This interface is not intended to be user-replaceable.
/// </summary>
public interface IHostApplicationLifetime
{
/// <summary>
/// Triggered when the application host has fully started.
/// </summary>
CancellationToken ApplicationStarted { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// Shutdown will block until this event completes.
/// </summary>
CancellationToken ApplicationStopping { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// Shutdown will block until this event completes.
/// </summary>
CancellationToken ApplicationStopped { get; }
/// <summary>
/// Requests termination of the current application.
/// </summary>
void StopApplication();
}
}
接下来就可以在相关枚举上注册事件啦,参考如下代码:
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var life = host.Services.GetRequiredService<IHostApplicationLifetime>();
life.ApplicationStopped.Register(() => {
Console.WriteLine("Application is shut down");
});
host.Run();
}