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

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

step1:pom引入spring boot Actoator依賴安全

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

step2:開啓shutdown endpoint,默認是關閉的,須要在application.properties中開啓shutdown endpointapp

endpoints.shutdown.enabled=true   #啓用shutdown
endpoints.shutdown.sensitive=false  #須要禁用密碼驗證,不然須要進行認證才能調用服務
curl

step3:調用shutdown服務:spring-boot

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

 

經過上面的設置便可實現關閉spring boot應用,可是你會發現,這樣會十分不安全,只要經過服務調用便可關閉應用,因此,具體應用中經常須要進行安全認證,好比藉助Spring boot security,步驟以下:url

step1:pom.xml添加security依賴spa

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

step2:開啓安全驗證,application.properties中變動配置:code

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

相關文章
相關標籤/搜索