转载自: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. quarkus依赖注入之十一:拦截器高级特性上篇(属性设置和重复使用)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 本篇是<quarkus依赖注入> ...

  2. 带你快速上手HetuEngine

    本文分享自华为云社区<[手把手带你玩转HetuEngine](一)HetuEngine快速上手>,作者:HetuEngine九级代言. HetuEngine是什么 HetuEngine是华 ...

  3. QTreeView自绘实现酷炫样式

    本篇文章结合笔者的经历,介绍一种通过重写QTreeView绘制事件,使用QPainter来实现好看的列表的方式. 导语 Hi,各位读者朋友,大家好.相信大家在日常的工作中,经常会接触到QTreeVie ...

  4. ChatGPT赋能低代码开发:打造智能应用的双重引擎

    摘要:本文摘自葡萄城低代码产品活字格的资深用户(格友超哥)所撰写的文章:<惊叹表现!活字格+ChatGPT:低代码开发智能应用的巨大潜力>. ChatGPT的functions函数使用方 ...

  5. 完美解决Content type ‘multipart/form-data;boundary=----------0467042;charset=UTF-8‘ not supported问题

    一.前言 ​ 今天在做文件上传功能出现了该问题,该接口如下: @PostMapping("/upload") public Boolean upload(@RequestParam ...

  6. 谈一谈电商API接口

    随着电商行业的快速发展,越来越多的企业开始意识到并利用API接口来提升其电商平台的功能和效率.但是,对于普通用户来说,对API接口可能还不太了解.那么,什么是API接口,特别是电商API接口呢?本文将 ...

  7. SQL - 5

    Smiling & Weeping ----我本不想和风讨论你,可风说可以替我去见你 第五章:SQL高级处理 5.1 窗口函数 5.1.1 窗口函数概念及基本的使用方法 窗口函数也称为OLAP ...

  8. 回归克里格、普通克里格插值在ArcGIS中的实现

      本文介绍基于ArcMap软件,实现普通克里格.回归克里格方法的空间插值的具体操作. 目录 1 背景知识准备 2 回归克里格实现 2.1 采样点与环境变量提取 2.2 子集要素划分 2.3 异常值提 ...

  9. git升级编译安装

    一.删除旧版本git 方法一. yum remove git -y (centos环境) apt-get remove git -y (Ubuntu环境) 方法二. which git [root@p ...

  10. Teamcenter RAC 开发之《新建Item》

    private TCComponentItem createOperation(String itemName,String itemType) { //obejct_name itemType tr ...