springboot gracefully closed
Application: When the service is shut down to upgrade the service, if there are still threads running, you can wait for a period of time to close the application; if the thread is not executed and close the application, a corresponding prompt will be output
********************************
Examples
*********************
config layer
GracefulShutDown
@Component
public class GracefulShutDown implements TomcatConnectorCustomizer,
ApplicationListener<ContextClosedEvent> {
private Logger logger= LoggerFactory.getLogger(GracefulShutDown.class);
private Connector connector;
@Override
public void customize(Connector connector) {
this.connector=connector;
}
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) { //容器关闭之前调用
this.connector.pause();
Executor executor=this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor){
ThreadPoolExecutor threadPoolExecutor=(ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown(); //若无线程运行,立即关闭线程池;若有线程运行则等待
try {
if (!threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS)){
//等待10s,为false表示线程池没有关闭,随后强制关闭,此时正在执行的任务中断,只执行了一部分,控制台输出warn日志
logger.warn("10秒后线程未关闭,将强制关闭");
}else {
System.out.println("线程池已关闭:"+ LocalDateTime.now());
} //为true,线程池已经关闭,任务执行完成
}catch (Exception e){
e.printStackTrace();
}
}
}
}
*********************
controller layer
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
try{
Thread.sleep(2000);
}catch (Exception e){
System.out.println(e.getMessage());
}
return "hello world";
}
@RequestMapping("/hello2")
public String hello2(){
try{
Thread.sleep(20000);
}catch (Exception e){
System.out.println(e.getMessage());
}
return "hello world";
}
}
**************************
Use test
/hello
Note: When ctrl + c completes task execution, the thread pool is immediately closed
/hello2
Note: When ctrl + c is executed, the task does not end, and the thread pool is not closed immediately; after 10s, the thread pool is forcibly closed, the task is not completed, and no result is returned.