Spring Boot 应用优雅关闭详解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@EnableConfigurationProperties(WebMvcProperties.class)
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Bean
public GracefulShutdown gracefulShutdown() {
return new GracefulShutdown();
}
}
class GracefulShutdown {
private static final Logger LOGGER = LoggerFactory.getLogger(GracefulShutdown.class);
private final ExecutorService executorService;
public GracefulShutdown() {
this.executorService = Executors.newSingleThreadExecutor();
}
public void shutdown() {
LOGGER.info("开始优雅关闭...");
executorService.shutdown();
try {
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow();
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
LOGGER.error("优雅关闭任务未能正常结束,强制终止");
}
}
} catch (InterruptedException ie) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
LOGGER.info("优雅关闭完成");
}
}
这个代码示例展示了如何在Spring Boot应用中实现优雅关闭。它定义了一个名为GracefulShutdown
的类,其中包含了关闭逻辑。在应用程序关闭时,它会尝试优雅地关闭一个单线程的ExecutorService
。如果在指定时间内线程池没有正常关闭,它会尝试强制关闭所有执行中的任务。这个例子对于需要优雅处理关闭请求的场景,如Web服务、后台任务调度等,提供了一个很好的实践。
评论已关闭