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
配置的值,并不会立即停机,而是知道程序回调中的逻辑运行完成。
更多
Views: 1,431 · Posted: 2022-09-26
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...