熟悉IIS的读者通常不会直接停止站点,而会选择点击Application Pools(应用程序池)中的Stop(停止)来停止一个站点,应用程序池在被停止后,新的请求会被响应503,负载均衡识别到503后,会把该请求负载到其他机器上,以保证业务不会中断。同样的问题,当点击Stop(停止)停止时,正在响应的请求,会发生什么情况呢。有经验的开发/运维会回答,在Application Pools(应用程序池)里Advanced Settings(高级设置)中Process Model(进程模型)组包含一个Shutdown Time Limit(关闭时间限制)选项,默认值为90s。这就意味着当应用程序池停止、回收时,IIS会最多等待没响应的请求90s,如果90s内,所有的请求响应完毕,应用程序池就会被停止、回收。那么如何判断IIS在这90s内未响应请求是否全部被响应呢,如果部署的程序是ASP.NET Core,可以在Event Viewer(事件查看器)/Windows Logs(Windows 日志)/Application(应用程序)里查看事件日志,如果出现Failed to gracefully shutdown application 'MACHINE/WEBROOT/APPHOST/xxx'.这个警告,则表明存在请求没有被响应,被IIS强行关闭的情况。
事与愿违,在实际生产实践中,读者会发现IIS并没有"等待"90s,就会关掉连接,而客户端还在傻傻等待90s后才会显示无响应,造成正在请求的HTTP无法响应。通过阅读[官方文档](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-8.0#ihostapplicationlifetime ".NET Generic Host in ASP.NET Core")我们得知,等ASP.NET Core收到关闭信号时,对于正在处理的HTTP请求,会等待5s,5s之后会像IIS那样关闭连接。所以我们需要设置HostOptions
//If the timeout period expires before all of the hosted services stop, any remaining active services are stopped when the app shuts down. The services stop even if they haven't finished processing. If services require more time to stop, increase the timeout.