在 Spring Boot
应用中实现优雅关闭可以确保应用在停止时能够妥善处理正在进行的任务、释放资源,避免数据丢失和系统异常。以下是几种实现 Spring Boot
应用优雅关闭的方法:
1. 使用 Spring Boot Actuator
Spring Boot Actuator
提供了一个 /shutdown
端点,可以用于优雅地关闭应用程序。
步骤
添加依赖:在 pom.xml
中添加 Spring Boot Actuator
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置端点:在 application.properties
或 application.yml
中启用 /shutdown
端点:
management.endpoints.web.exposure.include=shutdown
management.endpoint.shutdown.enabled=true
yaml
management:
endpoints:
web:
exposure:
include: shutdown
endpoint:
shutdown:
enabled: true
触发关闭:通过发送 POST 请求到 /actuator/shutdown
来触发应用的优雅关闭:
curl -X POST http://localhost:8080/actuator/shutdown
2. 实现 DisposableBean
或使用 @PreDestroy
注解
DisposableBean
接口
实现 DisposableBean
接口的 destroy
方法,该方法会在 Spring 容器关闭时自动调用。
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
@Component
public class MyDisposableBean implements DisposableBean {
@Override
public void destroy() throws Exception {
// 在这里执行清理操作,如关闭数据库连接、释放资源等
System.out.println("Performing cleanup operations...");
}
}
@PreDestroy
注解
使用 @PreDestroy
注解标记一个方法,该方法会在Bean
销毁之前执行。
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class MyPreDestroyBean {
@PreDestroy
public void cleanup() {
// 在这里执行清理操作
System.out.println("Cleaning up resources...");
}
}
3. 自定义关闭钩子
通过 Runtime.getRuntime().addShutdownHook()
方法添加自定义的关闭钩子,在应用关闭时执行特定的操作。
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class ShutdownHookExample implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// 在这里执行清理操作
System.out.println("Shutdown hook is running...");
}));
}
}
4. 使用 GracefulShutdown
功能(Spring Boot 2.3+)
Spring Boot 2.3 及以上版本提供了内置的 GracefulShutdown
功能,可以在应用关闭时等待一段时间,让正在进行的请求有足够的时间完成。
配置
在 application.properties
或 application.yml
中配置优雅关闭的超时时间:
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=10s
server:
shutdown: graceful
spring:
lifecycle:
timeout-per-shutdown-phase: 10s
上述配置表示在关闭应用时,会等待 10 秒让正在进行的请求完成。