使用actuator優雅地停止SpringBoot應用

優雅如何定義?

簡而言之,就是對應用進程發送停止指令之後,能夠保證正在執行的業務操作不受影響,可以繼續完成已有請求的處理,但是停止處理新來的請求。

在 Spring Boot 2.3及以後版本中增加了新特性:優雅停止,目前 Spring Boot 內置的四個嵌入式 Web 服務器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反應式和基於Servlet的Web應用程序都支持優雅停止。

Spring Boot 2.3 及以上版本優雅停止

首先創建一個 Spring Boot 的 Web 項目,版本選擇 2.3.0.RELEASE,Spring Boot 2.3.0.RELEASE內置的 Tomcat版本時9.0.35。

其中,優雅關閉內置Web容器的入口代碼在 

org.springframework.boot.web.embedded.tomcat 的 GracefulShutdown 裏,大概邏輯就是先停止外部的所有新請求,然後再處理關閉前收到的請求,有興趣的可以自己去看下。

內嵌的 Tomcat 容器平滑關閉的配置已經完成了,那麼如何優雅關閉 Spring 容器了,就需要 Actuator 來實現 Spring 容器的關閉了。

然後加入 actuator 依賴,依賴如下所示:

1

2

3

4

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

然後接着再添加一些配置來暴露 actuator 的 shutdown 接口:

注意此處的坑,下面的配置中,一個是endpoint,一個是endpoints,多了個s,不一樣的。

1

2

3

4

5

6

7

8

management:

  endpoint:

    shutdown:

      enabled: true

  endpoints:

    web:

      exposure:

        include: shutdown

啓動項目,此時訪問http://localhost/actuator會顯示支持的方法。

如果把上面配置中的shutdown換成*,會看到actuator支持的所有方法,如健康檢查、統計、監控、審計等,這裏不做介紹。

{

"_links": {

"self": {

"href": "http://localhost/actuator",

"templated": false

},

"shutdown": {

"href": "http://localhost/actuator/shutdown",

"templated": false

}

}

}

配置搞定後,然後創建一個DemoController控制器,並有一個 sayHi()方法,線程等待10s,用來模擬業務耗時處理,具體代碼如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package com.example.demo.controller;

 

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

 

/**

 * 優雅關閉springboot

 *

 * @author 架構師小跟班 jiagou1216.com

 */

@RestController

public class DemoController {

    @GetMapping("/sayHi")

    public String sayHi() throws InterruptedException {

        // 模擬複雜業務耗時處理流程

        Thread.sleep(10 * 1000L);

        return "success";

    }

}

啓動項目,使用postman測試 ,會等待10s後顯示請求成功,等待中......:

此時調用http://localhost/actuator/shutdown 就可以執行優雅地停止,返回結果如下:

{

    "message": "Shutting down, bye..."

}

如果在這個時候,發起新的請求 http://localhost/sayHi,會沒有反應,因爲服務已經“停止”了:

再回頭看第一個請求,返回了結果(10s後):success。

其中有幾條服務日誌如下:

2020-05-25 23:05:15.163 INFO 102724 --- [ Thread-253] o.s.b.w.e.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete

2020-05-25 23:05:15.287 INFO 102724 --- [tomcat-shutdown] o.s.b.w.e.tomcat.GracefulShutdown : Graceful shutdown complete

2020-05-25 23:05:15.295 INFO 102724 --- [ Thread-253] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

從日誌中可以看出來,當調用 shutdown 接口的時候,會先等待請求處理完畢後再優雅地停止。

注意:

如果使用瀏覽器調用http://localhost/actuator/shutdown方法,會報405,要用POST請求。

原文鏈接:

https://www.jiagou1216.com/blog/micro/861.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章