1. 程式人生 > >spring boot溫柔重啟

spring boot溫柔重啟

最近在使用spring boot 框架以微服務的形式開發專案,在閘道器層做了負載均衡,每次重啟的時候直接kill掉程序 然後重啟,但是其中會有一個問題,假如在重啟的時候還有任務在跑,正好執行一半的時候,但是程式被kill了,那就執行了一半,那麼資料就會有問題,所以直接用kill命令是有問題的,會造成資料缺失。

kill -9 程序id直接用這個命令據說也能行的通,但是我實驗了好幾次都是不行的,還是直接被殺死,沒有等我任務執行完成。

1.actuator方式

網上查了查發現spring有自己的方法

首先引入依賴包

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

//安全驗證依賴包
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

配置檔案,配置對應的引數:

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

security.user.name=userName         #使用者名稱
security.user.password=password     #密碼

management.security.role=XX_ROLE    #角色(我實驗沒有作用)

endpoints.shutdown.path=/shutdown     #重啟的url路徑

management.port=埠號    #指定管理埠

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

把連線的請求放進自己的shell腳本里面就可以了,每次重啟的時候,會檢測是否還有任務在跑,如果有任務在跑就不會關閉程序,會等任務執行完了在去結束程序

2.關閉上下文方式

第一種方式,我伺服器跑的時候curl請求開始的時候挺快的,但是過一會會特別慢,讓我放棄了這種做法。

@RestController
public class ShutdownController implements ApplicationContextAware {

    private ApplicationContext context;

    @PostMapping("/shutdownContext")
    public void shutdownContext() {
        ((ConfigurableApplicationContext) context).close();
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.context = ctx;

    }
    @PostMapping("/lalala")
    public void shutdownContex() {
        System.out.println("123123123");
    }

}

框架在接收請求的時候都會走上下文,只要關閉所有的上下文即可關閉程序,同樣也實現了優雅的關閉,測試結果一切都正常,和方式1 的預想結果都一樣。