[英]How can I safe to quit self-hosted application (do something before quit)
I want the self-hosted ASP.NET Core Application can delay a moment before quit when receive an exit signal. 我希望自托管的ASP.NET Core应用程序在收到退出信号时可以在退出之前延迟一会儿。
I have multiple instances of the application behind a load balancing. 我有一个负载平衡背后的应用程序的多个实例。
By default, if I shutdown an instance, the processing requests will be broken. 默认情况下,如果我关闭实例,则处理请求将被破坏。 And in a short time there are some new requests will still send to the offline instance because load balancing have an interval for health check. 而且在很短的时间内,由于负载平衡会定期进行健康检查,因此一些新请求仍将发送到脱机实例。
So if I can do something before quit: 因此,如果我可以在退出前做点事情:
Then, the application can be "safely" quit. 然后,可以“安全地”退出该应用程序。 It allows an instance to smoothly down and users will not feel it. 它允许实例平稳运行,用户不会感觉到它。
So I want if there is an official solution for that, or a best practice. 所以我想知道是否有官方的解决方案或最佳实践。
I want the self-hosted ASP.NET Core Application can delay a moment before quit when receive an exit signal. 我希望自托管的ASP.NET Core应用程序在收到退出信号时可以在退出之前延迟一会儿。
What is this signal? 这是什么信号? KILL or TERM? 杀还是杀?
Lets say that you want to handle TERM signal. 假设您要处理TERM信号。
So, if you are using .net Core 1.X, your solution would be something like this. 因此,如果您使用.net Core 1.X,则解决方案将是这样。 First, you need to add dependency to your json file 首先,您需要向json文件添加依赖项
"System.Runtime.Loader" : "<version>
Then you can handle SIGTERM event bi adding method to an event 然后,您可以处理SIGTERM事件的双向添加方法
AssemblyLoadContext.Default.Unloading += YourMethodThatWillHandleSignal;
For using .NET Core 2.X, there is different solution. 对于使用.NET Core 2.X,有不同的解决方案。 You can use IApplicationLifetime
interface ( documentation ). 您可以使用IApplicationLifetime
接口( 文档 )。
when you have this, all you can do is this: 当您拥有此功能时,您所能做的就是:
applicationLifetime.ApplicationStopping.Register(() => Console.WriteLine("Stopping"));
applicationLifetime.ApplicationStopped.Register(() => Console.WriteLine("Stopped"));
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.