拒绝 kill -9 强制停止,如何优雅停止 Spring Boot 服务?

1)程序正常退出

2)使用System.exit()

3)终端使用Ctrl+C

4)使用Kill pid干掉进程

那么如果你偏偏要kill -9 程序肯定是不知所措的。

而在Springboot中,其实已经帮你实现好了一个shutdownHook,支持响应Ctrl+c或者kill -15 TERM信号。

随便启动一个应用,然后Ctrl+c一下,观察日志就可知,它在AnnotationConfigEmbeddedWebApplicationContext这个类中打印出了疑似Closing…的日志,真正的实现逻辑在其父类

AbstractApplicationContext中(这个其实是spring中的类,意味着什么呢,在spring中就支持了对优雅停机的扩展)。

public void registerShutdownHook() {

if (this.shutdownHook == null) {

this.shutdownHook = new Thread() {

public void run() {

synchronized(AbstractApplicationContext.this.startupShutdownMonitor) {

AbstractApplicationContext.this.doClose();

}

}

};

Runtime.getRuntime().addShutdownHook(this.shutdownHook);

}

}

public void destroy() {

this.close();

}

public void close() {

Object var1 = this.startupShutdownMonitor;

synchronized(this.startupShutdownMonitor) {

this.doClose();

if (this.shutdownHook != null) {

try {

Runtime.getRuntime().removeShutdownHook(this.shutdownHook);

} catch (IllegalStateException var4) {

;

}

}

}

}

<
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值