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

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

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

  <dependency>

<groupId>org.springframework.bootgroupId>

<artifactId>spring-boot-starter-actuatorartifactId>

dependency>

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

server.port=3333

management.endpoint.shutdown.enabled=true

management.endpoints.web.exposure.include=shutdown

接下来,咱们创建一个 Spring Boot 工程,然后设置一个 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

*/

@Configuration

public 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();

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

/* 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

*/

@RestController

public 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;

}

}

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

总结

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

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

所谓技多不压身,我们所读过的每一本书,所学过的每一门语言,在未来指不定都能给我们意想不到的回馈呢。其实做为一个开发者,有一个学习的氛围跟一个交流圈子特别重要这里我推荐一个Java学习交流群私信小编回复JAVA获得进群资料,不管你是小白还是大牛欢迎入驻,大家一起交流成长。

python 程序停止打印日志_停止 Spring Boot 服务的几种优雅姿势相关推荐

  1. python 程序停止打印日志_优雅停止 SpringBoot 服务,拒绝 kill -9 暴力停止!

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

  2. Python程序可打印今天的年,月和日

    In the below example – we are implementing a python program to print the current/ today's year, mont ...

  3. springboot日志写入mysql_44. Spring Boot日志记录SLF4J【从零开始学Spring Boot】

    学院中有Spring Boot相关的课程!点击「阅读原文」进行查看! SpringSecurity5.0视频:http://t.cn/A6ZadMBe Sharding-JDBC分库分表实战: 在开发 ...

  4. logback日志pattern_003、Spring Boot使用slf4j进行日志记录

    在开发中,我们经常使用 System.out.println() 来打印一些信息,但是这样不好,因为大量的使用 System.out 会增加资源的消耗.我们实际项目中使用的是 slf4j 的 logb ...

  5. java开源springboot项目_使用Spring Boot的10多个免费开源项目

    这是一个真实的应用程序,为  Spring.io  网站提供支持.它正在生产中,每天都有成千上万的用户使用. 我强烈建议这个项目,你将学习有关Spring框架生态系统,Elasticsearch,Gr ...

  6. ssm如何支持热部署_最新Spring Boot实战文档推荐:项目搭建+配置+SSM整合

    在Spring Boot项目中,正常来说是不存在XML配置,这是因为Spring Boot不推荐使用XML,注意,排不支持,Spring Boot推荐开发者使用Java配置来搭建框架, Spring ...

  7. springboot做系统所需的软硬件环境_最新Spring Boot实战文档推荐:项目搭建+配置+SSM整合...

    在Spring Boot项目中,正常来说是不存在XML配置,这是因为Spring Boot不推荐使用XML,注意,排不支持,Spring Boot推荐开发者使用Java配置来搭建框架, Spring ...

  8. WebSocket 从入门到精通 -- Spring boot服务端客户端 -- HTML客户端

    注意:学习本文章一定要打开自己的开发工具,代码中有详细的解释.电脑不在身边建议先收藏,方便日后观看.最后祝大家技术突飞猛进,早日拿到心仪的offer. WebSocket -- 从入门到精通 基础讲解 ...

  9. 启动/关闭Spring boot服务脚本

    启动Spring boot服务脚本 #!/bin/bash cd /test java -jar test.jar &> ./test.log & echo "成功&q ...

最新文章

  1. 基于GAN模型的生成人脸重构、返老还童、看见前世今生(Age Progression/Regression)
  2. LeetCode Reconstruct Original Digits from English
  3. leetcode - two-sum
  4. 熟悉Redhat 9.0
  5. 使用字符串解析的方式完成计算器的设计思路
  6. Transifex与GTK文档翻译, Linux镜像文件, 外设接口杂谈
  7. SAP ABAP实用技巧介绍系列之反模式:一些低效的ABAP内表操作
  8. 关于群论证明费马小定理?
  9. ux设计中的各种地图_移动应用程序设计中的常见UX错误
  10. html翻转切换div效果,图片翻转效果
  11. node html5,html5前端入门教程分享:Node.Js 框架
  12. 多个表结果的并列显示
  13. JAVA实现UDP通信
  14. Linux系统中CPU占用率较高问题排查思路与解决方法
  15. html阅读封面代码,HTML5/SVG 书本封面设计
  16. 在线考试系统,在线考试后台管理
  17. 读书笔记app推荐——只为让你的生活更高效
  18. Android进阶知识树——Android消息队列
  19. 19n20c的参数_常用场效应管参数
  20. 什么是DNS劫持?如何进行有效应对?

热门文章

  1. (JAVA)集合Collection3
  2. linux+默认监听+目录,C# 时时监听目录文件改动
  3. 吉他谱----see you again
  4. 题解 P5301 【[GXOI/GZOI2019]宝牌一大堆】
  5. python学习笔记(十 三)、网络编程
  6. Deep learning with Python 学习笔记(9)
  7. ubuntu下软件中心闪退问题解决
  8. Flex 学习站点汇总,(FLEX学习站点、博客、论坛)
  9. [剑指offer]面试题第[58-2]题[JAVA][左旋转字符串][拼接]
  10. [Leetcode][JAVA][第912题][排序算法]