牛掰!Spring Boot 2.3.0 新特性:如何优雅停机?
回复“资源”获取独家整理的学习资料!
1.什么是优雅停机
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() throws InterruptedException {
// 模拟业务耗时处理流程
Thread.sleep(20 * 1000L);
return "hello";
}
}
2.graceful shutdown
3.配置体验
/**
* Configuration for shutting down a {@link WebServer}.
*
* @author Andy Wilkinson
* @since 2.3.0
*/
public enum Shutdown {
/**
* 优雅停机 (限期停机)
*
*/
GRACEFUL,
/**
* 立即停机
*/
IMMEDIATE;
}
-
请求服务端接口
-
执行关闭应用
-
服务端接到关闭指令
2020-05-17 18:28:28.940 INFO 60341 --- [extShutdownHook] o.s.b.w.e.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete
2020-05-17 18:28:45.923 INFO 60341 --- [tomcat-shutdown] o.s.b.w.e.tomcat.GracefulShutdown : Graceful shutdown complete
-
接口请求执行完成
4.相关知识
4.1 关于此处执行kill -2 而不是 kill -9
//ApplicationContext
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
@Override
public void run() {
synchronized (startupShutdownMonitor) {
doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
4.2
@Endpoint(id = "shutdown", enableByDefault = false)
public class ShutdownEndpoint implements ApplicationContextAware {
@WriteOperation
public Map<String, String> shutdown() {
Thread thread = new Thread(this::performShutdown);
thread.setContextClassLoader(getClass().getClassLoader());
thread.start();
}
private void performShutdown() {
try {
Thread.sleep(500L);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// 此处close 逻辑和上边 shutdownhook 的处理一样
this.context.close();
}
}
4.3
END
有热门推荐👇
1.
2.
3.
4.
文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*