Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Boot 优雅停机

Spring Boot Actuator 大约 1442 字

添加配置

默认是immediate立即停止。

server:
  shutdown: graceful

设置优雅停机超时时间,默认是30秒。

spring:
  lifecycle:
    timeout-per-shutdown-phase: 1m

停机方式

Linux kill 命令

使用kill -9无法触发优雅停机。

kill -15 <pid>

Spring Actuator

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

发送停机请求

curl -X POST --location "http://localhost:8080/actuator/shutdown" \
    -H "Accept: application/vnd.spring-boot.actuator.v3+json"

停机回调

Java层面的Runtime回调和Spring层面的@PreDestroy

@SpringBootApplication
public class ShutdownApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShutdownApplication.class, args);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println(LocalDateTime.now() + " runtime shutdown hook...");
        }));
    }

    @PreDestroy
    public void preDestroy() throws InterruptedException {
        System.out.println(LocalDateTime.now() + " pre destroy shutdown hook start...");
        Thread.sleep(40000);
        System.out.println(LocalDateTime.now() + " pre destroy shutdown hook end...");
    }

}

备注

测试中发现(基于Spring Boot2.7.3):如果Runtime@PreDestroy中的处理时间大于了spring.lifecycle.timeout-per-shutdown-phase配置的值,并不会立即停机,而是知道程序回调中的逻辑运行完成。

更多

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.application-exit

阅读 120 · 发布于 2022-09-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批