关于如何优雅停止Spring Boot应用的方案

基于目前Spring Boot应用需要使用Kill命令才能启动的问题,针对性地进行了甄别测试,最终,主要依赖Spring Boot Actuator的endpoint特性解决的。具体解决方案如下:

  • pom.xml中引入actuator依赖

   <dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-actuator</artifactId>

   </dependency>

如果出现版本错误,需要在<dependencyManagement>中增加相应的依赖管理项:

   <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>1.5.3.RELEASE</version>  

   <type>pom</type>

   <scope>import</scope>

   </dependency>

  • 开启shutdown endpoint

Spring Boot Actuator的shutdown endpoint默认是关闭的,因此在application.yml中开启shutdown endpoint:打开application.yml文件,增加配置项:

Spring boot 1.X 配置如下:

endpoints:

  shutdown:

    enabled: true

   sensitive: false

Spring Boot 2.X 配置如下:

management:

  endpoints:

    web:

      exposure:

        include: shutdown

  endpoint:

    shutdown:

      enabled: true #开启优雅关闭方式

  security:

    enabled: false #关闭安全认证

enabled是开启shutdown endpoint;sensitive是关闭密码认证(暂时方案,后期需要启动安全认证)。

  • 发送shutdown信号

shutdown的默认url为host:port/shutdown(Spring boot 2.x的连接为host:port/actuator/shutdown),当需要停止服务时,向服务器post该请求即可,如:

Spring boot 1.x连接如下:

curl -X POST http://localhost:8080/shutdown

Spring boot 2.x连接如下:

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

如果命令执行成功,返回:

相应的微服务就会停止:

 

 

在Eureka中的注册服务,刷新后随即消失:

 

最后,重新启动中止的微服务,启动成功,并在Eureka中正常运行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章