Spring Boot 2.3.0 新特性-优雅停机

2.3.0版本增加了新的特性--优雅停机

配置文件:

bootstrap.yml:

server:
# 设置优雅停机。默认值 IMMEDIATE 表示立即停机
  shutdown: graceful
spring:
  lifecycle:
# 最长等待时间,如果超时,立即停机
    timeout-per-shutdown-phase: 30s

停机方式

  • 使用 kill -2
    kill -9 是暴力停机,不会触发 ShutdownHook 事件
  @Override
  public void registerShutdownHook() {
    if (this.shutdownHook == null) {
      // No shutdown hook registered yet.
      this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
        @Override
        public void run() {
          synchronized (startupShutdownMonitor) {
            doClose();
          }
        }
      };
      Runtime.getRuntime().addShutdownHook(this.shutdownHook);
    }
  }
  • actuator/shutdown
    POST 请求 /actuator/shutdown

源码如下:

@Endpoint(id = "shutdown", enableByDefault = false)
public class ShutdownEndpoint implements ApplicationContextAware {

  @WriteOperation
  public Map<String, String> shutdown() {
    Thread thread = new Thread(this::performShutdown);
    thread.setContextClassLoader(getClass().getClassLoader());
    thread.start();
  }

  private void performShutdown() {
    try {
      Thread.sleep(500L);
    }
    catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
    }

    // 此处close 逻辑和上边 shutdownhook 的处理一样
    this.context.close();
  }
}

shutdown 节点默认是不暴露的,配置如下:

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    shutdown:
      enabled: true
    configprops:
      enabled: true

特别注意的是,web在endpoints下,但是shutdown和configprops等都在endpoint(没有s)下,这里坑了好久

停机后容器行为取决于具体的 web 容器行为

  • tomcat
    停止接收请求,客户端新请求等待超时。
  • Reactor Netty
    停止接收请求,客户端新请求等待超时。
  • Undertow
    停止接收请求,客户端新请求直接返回 503。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容