转载自: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. docker-compose快速部署elasticsearch-8.x集群+kibana

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 前文<Docker下elasticse ...

  2. 使用.NET Jieba.NET 的 PosSegmenter 实现中文分词匹配

    ​ 目录 引言 1. 什么是中文分词 2. Jieba.NET简介 3. PosSegmenter介绍 4. 实现中文分词匹配 4.1 安装Jieba.NET库 4.2 创建PosSegmenter实 ...

  3. 【Windows】KMS 激活命令记录

    目录 KMS 服务器激活 Office.Visio 推荐使用 office tool plus 部署并配置 KMS 激活 什么是 KMS? KMS 正版与否的区别 总结 KMS 服务器激活 利用 KM ...

  4. iOS交叉编译

    编译objc程序 ~/toolchain4/pre/bin/arm-apple-darwin9-gcc -arch arm -lobjc -framework CoreFoundation -fram ...

  5. Web端上传数据到OSS

    阿里云文档:参考文献 更正第三点:用户带着从服务器获取的数据签名和文件上传到OSS,这样做可以保证安全性.减轻服务器负担. 1.操作步骤 ①新建Bucket ②创建后更改跨域设置 这一步是保证跨域请胯 ...

  6. Solution -「洛谷 P7395」「CoE-I 2021C」弹珠游戏

    Description Link. 游戏在 \(4\times4\) 的菱形棋盘上进行: 两名玩家轮流放置弹珠,可以在横向.纵向.\(45\) 度斜线.\(135\) 度斜线方向未放置弹珠的位置连续放 ...

  7. MySQL 高级(进阶) SQL 语句

    MySQL 高级(进阶) SQL 语句 use gy; create table location (Region char(20),Store_Name char(20)); insert into ...

  8. DevOps|破除壁垒,重塑协作-业务闭环释放产研运协作巨大效能

    - 会议太多了,员工开会效率降低了50%! 上篇文章<研发效能组织架构:职能独立vs业务闭环>介绍了职能独立型组织架构和业务闭环型组织架构的特点,优劣势.也许有的小伙伴可能对这两种组织架构 ...

  9. fprintf

    fprintf 是一个标准C库函数,用于将格式化的输出写入到指定文件流中.它的函数原型如下: int fprintf(FILE *stream, const char *format, ...); 参 ...

  10. Django框架项目之上线——docker、部署上线

    文章目录 Docker CentOS安装Docker 设置管理Docker的仓库 安装Docker Engine-Community Docker基础命令 开启关闭 镜像操作 容器操作 Docker安 ...