【SpringBoot筆記】SpringBoot如何正確關閉應用


關閉Spring Boot應用程序,我們可以通過OS命令kill -9 進程ID 實現將進程殺死。但是,有沒有一種更好的方式,比如通過REST請求實現?Spring Boot Actoator提供了實現。通過提供的shutdown服務可以實現安全的關閉Spring Boot應用。簡單實用步驟如下:

step1:pom引入spring boot Actoator依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

step2:開啟shutdown endpoint,默認是關閉的,需要在application.properties中開啟shutdown endpoint

endpoints.shutdown.enabled=true   #啟用shutdown
endpoints.shutdown.sensitive=false  #需要禁用密碼驗證,否則需要進行認證才能調用服務

step3:調用shutdown服務:

shutdown的默認urlhost:port/shutdown,當需要停止服務時,向服務器post該請求即可,如:
curl -X POST host:port/shutdown
將得到形如{"message":"Shutting down, bye..."}的響應

 

通過上面的設置即可實現關閉spring boot應用,但是你會發現,這樣會十分不安全,只要通過服務調用即可關閉應用,所以,具體應用中常常需要進行安全認證,比如借助Spring boot security,步驟如下:

step1:pom.xml添加security依賴

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>

step2:開啟安全驗證,application.properties中變更配置:

endpoints.shutdown.sensitive=true #開啟shutdown的安全驗證

security.user.name=userName    #用戶名

security.user.password=password             #密碼

management.security.role=XX_ROLE#角色

step3:指定路徑、IP、端口

endpoints.shutdown.path=/custompath     #指定shutdown的路徑,如果需要統一指定應用的路徑,則可以用management.context-path=/manage

management.port=XXX    #指定管理端口

management.address=X.X.X.X  #指定客戶端ID

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM