转载自:https://blog.csdn.net/qq_26323323/article/details/89814410

2020/02/26重新编辑一下

前面介绍ShutDownHook的基本使用方法,但是没有清楚的表述如何在SpringBoot中运用,这里我们来补充一下:

查阅SpringBoot官方文档有这么一段描述:

1.10. Application Exit

Each SpringApplication registers a shutdown hook with the JVM to ensure that the ApplicationContext closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface or the @PreDestroy annotation) can be used.

官方介绍了两种方法:

1. 直接实现DisposableBean接口,实现destroy方法即可

@Slf4j
@Component
public class CustomShutdownHook implements DisposableBean { @Override
public void destroy() throws Exception {
} }

2. 在方法上使用@PreDestroy注解,类似@PostConstruct注解使用方法。

1. Runtime.addShutDownHook(Thread hook)

// 创建HookTest,我们通过main方法来模拟应用程序
public class HookTest { public static void main(String[] args) { // 添加hook thread,重写其run方法
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
System.out.println("this is hook demo...");
// TODO
}
}); int i = 0;
// 这里会报错,我们验证写是否会执行hook thread
int j = 10/i;
System.out.println("j" + j);
}
}

2. Runtime.addShutDownHook(Thread hook)应用场景

* 程序正常退出

* 使用System.exit()

* 终端使用Ctrl+C触发的中断

* 系统关闭

* OutofMemory宕机

* 使用Kill pid杀死进程(使用kill -9是不会被调用的)

3. Spring如何添加钩子函数

// 通过这种方式来添加钩子函数
ApplicationContext.registerShutdownHook(); // 通过源码可以看到,
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread() {
@Override
public void run() {
synchronized (startupShutdownMonitor) {
doClose();
}
}
};
// 也是通过这种方式来添加
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
} // 重点是这个doClose()方法 protected void doClose() {
// Check whether an actual close attempt is necessary...
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isInfoEnabled()) {
logger.info("Closing " + this);
} LiveBeansView.unregisterApplicationContext(this); try {
// Publish shutdown event.
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
} // Stop all Lifecycle beans, to avoid delays during individual destruction.
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
} // Destroy all cached singletons in the context's BeanFactory.
destroyBeans(); // Close the state of this context itself.
closeBeanFactory(); // Let subclasses do some final clean-up if they wish...
onClose(); // Switch to inactive.
this.active.set(false);
}
}

可以看到:doClose()方法会执行bean的destroy(),也会执行SmartLifeCycle的stop()方法,我们就可以通过重写这些方法来实现对象的关闭,生命周期的管理,实现平滑shutdown

Spring优雅关闭之:ShutDownHook的更多相关文章

  1. 如何优雅关闭 Spring Boot 应用

    ## 前言 随着线上应用逐步采用 SpringBoot 构建,SpringBoot应用实例越来多,当线上某个应用需要升级部署时,常常简单粗暴地使用 kill 命令,这种停止应用的方式会让应用将所有处理 ...

  2. 如何在 Spring Boot 优雅关闭加入一些自定义机制

    个人创作公约:本人声明创作的所有文章皆为自己原创,如果有参考任何文章的地方,会标注出来,如果有疏漏,欢迎大家批判.如果大家发现网上有抄袭本文章的,欢迎举报,并且积极向这个 github 仓库 提交 i ...

  3. SpringBoot如何优雅关闭(SpringBoot2.3&Spring Boot2.2)

    SpringBoot如何优雅关闭(SpringBoot2.3&Spring Boot2.2) 优雅停止&暴力停止 暴力停止:像日常开发过程中,测试区或者本地开发时,我们并不会考虑项目关 ...

  4. Spring-IOC 在非 web 环境下优雅关闭容器

    当我们设计一个程序时,依赖了Spring容器,然而并不需要spring的web环境时(Spring web环境已经提供了优雅关闭),即程序启动只需要启动Spring ApplicationContex ...

  5. 从prototype beandefinition 谈 spring 的关闭流程和 prototype 的特性

    背景介绍: 服务端期望使用 面向对象编程, 和 spring 结合的话只能是通过 prototype 的 bean 定义,并通过 getBean 获取. 优雅停机探究: 代码说明: 1. 类关系 Si ...

  6. 优雅关闭服务下线(Jetty)

    在很多时候 kill -9 pid并不是很友好的方法,那样会将我们正在执行请求给断掉,同时eureka 中服务依旧是处于在线状态,这个时候我们可以使用官方提供的actuator来做优雅的关闭处理 - ...

  7. spring cloud: 关闭ribbon负载均衡

    spring cloud: 关闭ribbon负载均衡 1.eureka服务 2.2个user服务:7900/7901 3,movie服务 movie服务去请求 user的用户信息,而此时只想请求790 ...

  8. Socket编程中的强制关闭与优雅关闭及相关socket选项

    以下描述主要是针对windows平台下的TCP socket而言. 首先需要区分一下关闭socket和关闭TCP连接的区别,关闭TCP连接是指TCP协议层的东西,就是两个TCP端之间交换了一些协议包( ...

  9. 使用RunTime.getRunTime().addShutdownHook优雅关闭线程池

    有时候我们用到的程序不一定总是在JVM里面驻守,可能调用完就不用了,释放资源. RunTime.getRunTime().addShutdownHook的作用就是在JVM销毁前执行的一个线程.当然这个 ...

  10. 优雅关闭web服务的方式

    优雅关闭web服务 DBHelper, err = gorm.Open("mysql", "root:root@(115.159.59.129:3306)/test?ch ...

随机推荐

  1. AWD-PWN流量监控与抄流量反打

    RE手 在AWD中比较做牢,队伍里也没pwn手,在awd出现pwn靶机比较坐牢.之前都不知道pwn靶机可以抄流量反打. 参考pwn_waf:https://github.com/i0gan/pwn_w ...

  2. PRACK消息

    概述 PRACK消息是sip协议的扩展,在RFC3262中定义,标准的名称是sip协议中的可靠临时响应. 本文简单介绍标准中对PRACK消息流程的描述,以及fs配置PRACK的方式. 环境 cento ...

  3. 你能看到这个汉字么“  ” ?关于Unicode的私人使用区(PUA) 和浏览器端显示处理

    如果你现在使用的是chrome查看那么你是看不到我标题中的汉字的,显示为一个小方框,但是你使用edge查看的话,这个字就能正常的显示出来,不信你试试! 本故事源于我在做数据过程中遇到Unicode编码 ...

  4. ETL之apache hop系列4-hop开发数据增量同步功能

    ETL增量数据抽取CDC 概念:Change Data Capture,变化的数据捕获,也称:[增量数据抽取](名词解释) CDC是一种实现数据的增量抽取解决方案,是实现[ETL整体解决方案]中的一项 ...

  5. 详解 canal 同步 MySQL 增量数据到 ES

    canal 是阿里知名的开源项目,主要用途是基于 MySQL 数据库增量日志解析,提供增量数据订阅和消费. 这篇文章,我们手把手向同学们展示使用 canal 将 MySQL 增量数据同步到 ES . ...

  6. 初露头角!Walrus入选服贸会“数智影响力”数字化转型创新案例

    9月5日,由北京市通信管理局.工业和信息化部新闻宣传中心联合主办的"企业数字化转型论坛"在2023中国国际服务贸易交易会期间召开,论坛以"数字化引领 高质量发展" ...

  7. 一文搞懂 OTP 双因素认证

    GitHub 在 2023 年 3 月推出了双因素认证(two-factor authentication)简称 2FA,并且承诺所有在 GitHub 上贡献的开发者在 2023 年底前启用双因素认证 ...

  8. 运行在容器中Postgres数据库数据损坏后如何恢复?

    前言 在使用 K8S 部署 RSS 全套自托管解决方案- RssHub + Tiny Tiny Rss, 我介绍了将 RssHub + Tiny Tiny RSS 部署到 K8s 集群中的方案. 其中 ...

  9. linux内核离线升级步骤详解【亲测可用】

    由于种种原因,linux的内核版本需要升级,但由于生产原因往往不能在线升级,在此记录笔者本人昨晚的的离线升级步骤,亲测可用. 我们知道,红帽和CentOS同源同宗,内核升级步骤也是一样的. 目录 ■ ...

  10. centos7 oracle11gR2安装

    CentOS7安装Oracle 11gR2 图文详解 摘自: http://www.linuxidc.com/Linux/2016-04/130559.htm 最近要运维一个项目,准备在家办公,公司无 ...