在使用Springboot的时候,都要涉及到服务的停止和启动,当我们停止服务的时候,很多时候大家都是kill -9 直接把程序进程杀掉,这样程序不会执行优雅的关闭。而且一些没有执行完的程序就会直接退出。

  我们很多时候都需要安全的将服务停止,也就是把没有处理完的工作继续处理完成。比如停止一些依赖的服务,输出一些日志,发一些信号给其他的应用系统,这个在保证系统的高可用是非常有必要的。那么咱么就来看一下几种停止springboot的方法。

  第一种就是Springboot提供的actuator的功能,它可以执行shutdown, health, info等,默认情况下,actuator的shutdown是disable的,我们需要打开它。首先引入acturator的maven依赖。

  org.springframework.boot        spring-boot-starter-actuator    

  然后将shutdown节点打开,也将/actuator/shutdown暴露web访问也设置上,除了shutdown之外还有health, info的web访问都打开的话将management.endpoints.web.exposure.include=*就可以。将如下配置设置到application.properties里边。设置一下服务的端口号为3333。

server.port=3333management.endpoint.shutdown.enabled=truemanagement.endpoints.web.exposure.include=shutdown

  接下来,咱们创建一个springboot工程,然后设置一个bean对象,配置上PreDestroy方法。这样在停止的时候会打印语句。bean的整个生命周期分为创建、初始化、销毁,当最后关闭的时候会执行销毁操作。在销毁的方法中执行一条输出日志。

package com.hqs.springboot.shutdowndemo.bean;import javax.annotation.PreDestroy;/** * @author huangqingshi * @Date 2019-08-17 */public class TerminateBean {    @PreDestroy    public void preDestroy() {        System.out.println("TerminalBean is destroyed");    }}

  做一个configuration,然后提供一个获取bean的方法,这样该bean对象会被初始化。

package com.hqs.springboot.shutdowndemo.config;import com.hqs.springboot.shutdowndemo.bean.TerminateBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author huangqingshi * @Date 2019-08-17 */@Configurationpublic class ShutDownConfig {    @Bean    public TerminateBean getTerminateBean() {        return new TerminateBean();    }}

  在启动类里边输出一个启动日志,当工程启动的时候,会看到启动的输出,接下来咱们执行停止命令。

curl -X POST http://localhost:3333/actuator/shutdown

  以下日志可以输出启动时的日志打印和停止时的日志打印,同时程序已经停止。是不是比较神奇。

  第二种方法也比较简单,获取程序启动时候的context,然后关闭主程序启动时的context。这样程序在关闭的时候也会调用PreDestroy注解。如下方法在程序启动十秒后进行关闭。

        /* method 2: use ctx.close to shutdown all application context */        ConfigurableApplicationContext ctx = SpringApplication.run(ShutdowndemoApplication.class, args);        try {            TimeUnit.SECONDS.sleep(10);        } catch (InterruptedException e) {            e.printStackTrace();        }        ctx.close();

  第三种方法,在springboot启动的时候将进程号写入一个app.pid文件,生成的路径是可以指定的,可以通过命令 cat /Users/huangqingshi/app.id | xargs kill 命令直接停止服务,这个时候bean对象的PreDestroy方法也会调用的。这种方法大家使用的比较普遍。写一个start.sh用于启动springboot程序,然后写一个停止程序将服务停止。  

/* method 3 : generate a pid in a specified path, while use command to shutdown pid :            'cat /Users/huangqingshi/app.pid | xargs kill' */        SpringApplication application = new SpringApplication(ShutdowndemoApplication.class);        application.addListeners(new ApplicationPidFileWriter("/Users/huangqingshi/app.pid"));        application.run();

  第四种方法,通过调用一个SpringApplication.exit()方法也可以退出程序,同时将生成一个退出码,这个退出码可以传递给所有的context。这个就是一个JVM的钩子,通过调用这个方法的话会把所有PreDestroy的方法执行并停止,并且传递给具体的退出码给所有Context。通过调用System.exit(exitCode)可以将这个错误码也传给JVM。程序执行完后最后会输出:Process finished with exit code 0,给JVM一个SIGNAL。

          /* method 4: exit this application using static method */        ConfigurableApplicationContext ctx = SpringApplication.run(ShutdowndemoApplication.class, args);        exitApplication(ctx);
    public static void exitApplication(ConfigurableApplicationContext context) {        int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);        System.exit(exitCode);    }

  第五种方法,自己写一个Controller,然后将自己写好的Controller获取到程序的context,然后调用自己配置的Controller方法退出程序。通过调用自己写的/shutDownContext方法关闭程序:curl -X POST http://localhost:3333/shutDownContext。

package com.hqs.springboot.shutdowndemo.controller;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;/** * @author huangqingshi * @Date 2019-08-17 */@RestControllerpublic class ShutDownController implements ApplicationContextAware {    private ApplicationContext context;    @PostMapping("/shutDownContext")    public String shutDownContext() {        ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) context;        ctx.close();        return "context is shutdown";    }    @GetMapping("/")    public String getIndex() {        return "OK";    }    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        context = applicationContext;    }}

  好了,springboot的优雅关闭方法也都实现好了,也有同学问,如何暴力停止呢,简单,直接kill -9 相应的PID即可。

  总结一下:

  以上这几种方法实现的话比较简单,但是真实工作中还需要考虑的点还很多,比如需要保护暴露的点不被别人利用,一般要加一些防火墙,或者只在内网使用,保证程序安全。

  在真实的工作中的时候第三种比较常用,程序中一般使用内存队列或线程池的时候最好要优雅的关机,将内存队列没有处理的保存起来或线程池中没处理完的程序处理完。但是因为停机的时候比较快,所以停服务的时候最好不要处理大量的数据操作,这样会影响程序停止。

  好了,大家觉得还没看全的话,可以访问我的GIT代码:https://github.com/stonehqs/shutdowndemo.git 。

springboot 优雅关闭_Springboot 优雅停止服务的几种方法相关推荐

  1. springboot 优雅停机_SpringBoot 优雅停止服务的几种方法 第309篇

    相关历史文章(阅读本文之前,您可能需要先看下之前的系列?) 国内最全的Spring Boot系列之三 一分钟get:缓存穿透.缓存击穿.缓存雪崩 - 第304篇 布隆过滤器Bloom Filter竟然 ...

  2. controller调用controller的方法_SpringBoot 优雅停止服务的几种方法

    转自:博客园,作者:黄青石 www.cnblogs.com/huangqingshi/p/11370291.html 在使用 SpringBoot 的时候,都要涉及到服务的停止和启动,当我们停止服务的 ...

  3. SpringBoot 优雅停止服务的几种方法

    方法一 Springboot提供的actuator的功能,它可以执行shutdown, health, info <dependency><groupId>org.spring ...

  4. Spring Boot 优雅停止服务的几种方法

    作者 | 黄青石 来源 | https://www.cnblogs.com/huangqingshi/p/11370291.html 最近突然想到了优雅停止 SpringBoot 服务问题,在使用 S ...

  5. 停止计算机sql服务,SQL Server启动和停止服务的三种方法

    一.为什么要启动SQL Server服务? 1.如果你不开启服务,去连接数据会出现报错信息 2.因为不连接到服务器,就对数据库操作不了 二.启动SQL Server的三种方法 第一种:后台启动服务 * ...

  6. springboot 优雅关闭_springboot优雅的关闭应用

    使用actuator,通过发送http请求关闭 将应用注册为linux服务,通过service xxx stop关闭 具体这两种方式如何实现,这里就不说了,网上百度一堆,主要讲一下在这两种情况下web ...

  7. SpringBoot 优雅停止服务的几种方法 - 第309篇

    相关历史文章(阅读本文之前,您可能需要先看下之前的系列

  8. 打开和关闭mysql服务的两种方法

    方法一:使用cmd命令 首先,打开我们的dos窗口,开始-运行-输入cmd. 如上图所示,输入net start mysql 回车即可启动,输入net stop mysql 回车即可关闭. 方法二:选 ...

  9. 回答我,停止 Goroutine 有几种方法?

    大家好,我是煎鱼. 协程(goroutine)作为 Go 语言的扛把子,经常在各种 Go 工程项目中频繁露面,甚至有人会为了用 goroutine 而强行用他. 在 Go 工程师的面试中,也绕不开他, ...

最新文章

  1. java iris_利用K-Means聚类算法实现对iris.data.ulab
  2. Android事件机制:事件传递和消费
  3. python正则匹配html标签_Python正则获取、过滤或者替换HTML标签的方法
  4. 打破情感分类准确率 80 分天花板!更加充分的知识图谱结合范式
  5. @vail 判断某字段在范围内_怎么判断一台二次元影像测量仪的可靠性?
  6. 学习webpack前的准备工作
  7. java lambda 两个冒号_java lambda 表达式中的双冒号的用法说明 ::
  8. function在mysql里总是出错_如何在MySQL函数中引发错误
  9. FISCO BCOS(八)——— 一键部署 WeBase
  10. JZOJ1286太空电梯
  11. 虚拟机ESXi6.7安装黑群晖教程
  12. 《信息学奥赛一本通·初赛真题解析》
  13. exynos4412,tegra3,msm8960性能对比,参考对照exynos4210
  14. 基于SDCC的工程化实践
  15. 解决问题最高明的方法:打开自己
  16. mysql报1142错误
  17. 追尾事故降发生:超低功耗滴滴桔视ADAS落地实践
  18. vscode-remote 无法写入文件“vscode-remote://ssh-remote
  19. linux常用命令及ip地址更改
  20. x3d:了解x3dom

热门文章

  1. VS CODE Python开发环境配置
  2. 如何让Excel单元格中的名字分散对齐
  3. 认识Linux系统中的inode,硬链接和软链接
  4. 基于HOG特征的Adaboost行人检测
  5. ASP.NET入门教程:服务器控件
  6. stackoverflow favorites
  7. 正在中止线程 异常处理
  8. ICCV 2019 | RankSRGAN:排序学习 + GAN 用于超分辨率
  9. 快了!CVPR 2019 所有录用论文题目列表刊出,即将开放下载!
  10. Java 进阶之路:异常处理的内在原理及优雅的处理方式