Spring Boot整合优雅关机
# 优雅关机
application.yml
server:
shutdown: graceful # 开启优雅关机,默认IMMEDIATE是立即关机
management:
endpoint:
shutdown:
enabled: true
endpoints:
web:
exposure:
include: "shutdown"
base-path: /monitor
在使用若依框架实践中发现,似乎不需要此配置也可以实现优雅停机;而此并不会等待线程池的任务完成才关闭,需要再进行以下配置
# 优雅关闭线程池
@Bean
public ThreadPoolTaskExecutor collectThreadPoolExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(16);
executor.setMaxPoolSize(96);
executor.setQueueCapacity(1024);
executor.setKeepAliveSeconds(30);
executor.setThreadNamePrefix("xxxx任务");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
// 优雅关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
参考
- Java 并发编程 - 线程池优雅关闭(四) - 掘金 (opens new window)
- 线程池:ThreadPoolExecutor 和 ThreadPoolTaskExecutor 简述 – 古红色阿尔卑斯棒棒糖 (opens new window)
# 记一个坑
在实践中发现,使用在 Linux 下使用 kill -2 pid
并不是实现优雅关闭程序,需要配合 actuator
参考
上次更新: 2022/12/31, 03:04:26