Spring Boot 2.3.0 新特性-优雅停机

2020-05-20  本文已影响0人  EdgeE

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

配置文件:

bootstrap.yml:

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

停机方式

  @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);
    }
  }

源码如下:

@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 容器行为

上一篇下一篇

猜你喜欢

热点阅读