1. 程式人生 > >安全地停止SpringBoot應用服務

安全地停止SpringBoot應用服務

1. 在pom.xml中引入actuator依賴

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

2. 開啟shutdown endpoint

Spring Boot Actuatorshutdown endpoint預設是關閉的,因此在application.properties中開啟shutdown endpoint

#啟用shutdown
endpoints.shutdown.enabled=true #禁用密碼驗證 endpoints.shutdown.sensitive=false

3. 傳送shutdown訊號

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

4. 安全設定

可以看出,使用該方法可以非常方便的進行遠端操作,但是需要注意的是,正式使用時,必須對該請求進行必要的安全設定,比如藉助spring-boot-starter-security

進行身份認證:

  1. pom.xml新增security依賴

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  2. 開啟安全驗證
    application.properties中變更配置,並

    #開啟shutdown的安全驗證
    endpoints.shutdown.sensitive=true
    #驗證使用者名稱
    security.user.name=admin
    #驗證密碼
    security.user.password=secret #角色 management.security.role=SUPERUSER
  3. 指定路徑、IP、埠

    #指定shutdown endpoint的路徑
    endpoints.shutdown.path=/custompath
    #也可以統一指定所有endpoints的路徑`management.context-path=/manage`
    #指定管理埠和IP
    management.port=8081
    management.address=127.0.0.1