關於如何優雅停止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中正常運行。

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