公司去年开始逐步在容器化应用中实现优雅关闭,我们可以认为正常的优雅停机包括两个部分:应用 & 平台。
1. 应用
优雅退出,应用层需要做的任务是处理SIGTERM信号。应用自身需要实现优雅停机的处理逻辑,确保处理中的请求可以继续完成,资源得到有效的关闭释放,等等。
Spring boot (2.3.0及以上)官方文档:
Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest phase of stopping SmartLifecycle
beans. This stop processing uses a timeout which provides a grace period during which existing requests will be allowed to complete but no new requests will be permitted. The exact way in which new requests are not permitted varies depending on the web server that is being used. Jetty, Reactor Netty, and Tomcat will stop accepting requests at the network layer. Undertow will accept requests but respond immediately with a service unavailable (503) response.
1.1 配置
To enable graceful shutdown, configure the server.shutdown
property, as shown in the following example:
server.shutdown=graceful
To configure the timeout period, configure the spring.lifecycle.timeout-per-shutdown-phase
property, as shown in the following example:
spring.lifecycle.timeout-per-shutdown-phase=20s
下面是 Yaml 配置:
# 开启优雅关闭
server:
shutdown: graceful
# 关闭的缓冲时间
spring:
lifecycle:
timeout-per-shutdown-phase: 10s
1.2 源码分析
优雅停机在stop SmarLifecycle bean 的初始阶段,作为关闭应用程序上下文的一部分发生:
public interface SmartLifecycle extends Lifecycle, Phased {
int DEFAULT_PHASE = 2147483647;
default boolean isAutoStartup() {
return true;
}
default void stop(Runnable callback) {
this.stop();
callback.run();
}
default int getPhase() {
return 2147483647;
}
}
public final class WebServerGracefulShutdownLif