容器应用优雅关闭

公司去年开始逐步在容器化应用中实现优雅关闭,我们可以认为正常的优雅停机包括两个部分:应用 & 平台。

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值