1. 程式人生 > >SpringBoot正確、安全地關閉服務

SpringBoot正確、安全地關閉服務

前言

我們利用遠端關閉功能可以實現優雅地關閉指定地服務。

正文

本文依然使用v1.5.8.RELEASE ,講地是利用actuatorEndpoints實現關閉服務

首先準備一個eureka服務,然後啟動他。

然後準備一個eureka客戶端服務,客戶端的pom除了必要的springboot的web依賴還需要新增依賴如下

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

在eureka客戶端服務的application.properties檔案開啟shutdown endpoint,SpringBoot的endpoints.shutdown.enabled預設是關閉的。

eureka.client.service-url.defaultZone=http://admin:[email protected]:1111/eureka/
server.port=8762
spring.application.name=eureka-client
#啟用shutdown
endpoints.shutdown.enabled=true
#禁用密碼驗證
endpoints.shutdown.sensitive=false

#如果用的2.x版本的 就用註釋的那四行配置
#management.endpoints.shutdown.enabled=true
#management.endpoints.health.enabled=true
#management.endpoints.web.base-path=/
#management.endpoints.web.exposure.include=*

配置已經配好,這時可以啟動服務了,將他註冊在eureka上面,這時我們可以看到下面

然後在終端執行 curl -X POST 127.0.0.1:8762/shutdown ,可以看到message:Shutting down,bye...說明成功關閉了服務

下面筆者要教給大家一種高階使用的方法,做了一個安全的認證,上面關閉服務的缺點大家顯而易見,知道服務埠和ip的就能關閉,這種做法很不安全,接下來要在客戶端服務配置一下安全認證。

首先在eureka客戶端服務的application.properties檔案追加配置

eureka.client.service-url.defaultZone=http://admin:
[email protected]
:1111/eureka/ server.port=8762 spring.application.name=eureka-client management.security.enabled=true #啟用shutdown endpoints.shutdown.enabled=true #禁用密碼驗證 endpoints.shutdown.sensitive=true #驗證使用者名稱 security.user.name=admin #驗證密碼 security.user.password=admin #角色 management.security.role=SUPERUSER #指定shutdown endpoint的路徑 endpoints.shutdown.path=/custompath #也可以統一指定所有endpoints的路徑`management.context-path=/manage` #指定管理埠和IP management.port=8081 management.address=127.0.0.1

我們使用了security,就需要在pom新增依賴

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

大功告成,是不是很簡單,下面啟動你的客戶端服務,這裡我就不貼一些多餘的圖片了,成功註冊到eureka上面了,和上面的圖一樣。

接下來使用終端訪問 curl -X POST -u admin:admin 127.0.0.1:8081/custompath

看見了你的服務又和你say byebye了吧! 

這個命令  curl -X POST -u admin:admin 127.0.0.1:8081/custompath  每一個位置對應的引數值大家可以看application.properties檔案分別對應了哪些配置就明白了。

路過的大佬,看到這裡給個贊吧!