Spring Boot 优雅停机

Spring Boot Actuator About 1,442 words

添加配置

默认是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

Views: 1,460 · Posted: 2022-09-26

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh