最新的 Spring Boot 2.3 發布快半個月了:
https://spring.io/blog/2020/05/15/spring-boot-2-3-0-available-now
其中有個新特性叫:Graceful shutdown(優雅關閉)
之前也分享過這樣的文章,現在竟然出品官方姿勢了,新功能嘛,肯定得去官方看下,下面是官方的說明:
Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. When a grace period is configured, upon shutdown, the web server will no longer permit new requests and will wait for up to the grace period for active requests to complete.
下面,棧長給大家總結下:
優雅關閉支持所有 4 個嵌入式 Web 服務器:Jetty, Reactor Netty, Tomcat, Undertow,以及響應式的和基於 Servlet 的 Web 應用程序。
當配置了一個優雅關閉的緩沖時間,直到應用程序關閉時,Web 服務器都不再允許接收新的請求,緩沖時間是為了等待目前所有進行中的活動請求處理完成。
需要說明的是,Tomcat、Jetty 在網絡層會立即停止接收請求,而 Undertow 可以繼續接收請求,但會立即返回 503 服務不可用錯誤。
注意:Tomcat 生效版本需要:9.0.33+
怎么開啟優雅關閉?
下面是 Yaml 文件的配置示例:
# 開啟優雅關閉
server:
shutdown: graceful
# 關閉的緩沖時間
spring:
lifecycle:
timeout-per-shutdown-phase: 10s
源碼分析
上面介紹了優雅關閉參數的配置方式,下面我們通過源碼來看下默認的配置是什么。
先看第一個參數配置接收類:
org.springframework.boot.autoconfigure.web.ServerProperties
public enum Shutdown {
GRACEFUL,
IMMEDIATE;
private Shutdown() {
}
}
如源碼所示,默認為:IMMEDIATE
,所以優雅關閉是大家根據業務需要手動開啟的。
再來看第二個參數配置接收類:
org.springframework.boot.autoconfigure.context.LifecycleProperties
如源碼所示,默認緩沖時間為:30 秒。
再看下優雅關閉的源碼:
根據 Graceful
可以找到幾個相關的類,我們進入 Tomcat 的:
org.springframework.boot.web.embedded.tomcat.GracefulShutdown
public enum GracefulShutdownResult {
/**
* Requests remained active at the end of the grace period.
*/
REQUESTS_ACTIVE,
/**
* The server was idle with no active requests at the end of the grace period.
*/
IDLE,
/**
* The server was shutdown immediately, ignoring any active requests.
*/
IMMEDIATE;
}
REQUESTS_ACTIVE
說的是在緩沖期結束前連接保持活動狀態,也就是雖然官方默認給你 30 秒的緩存時間來處理囤積請求,如果 30 秒之后還沒處理完成,最后 Spring Boot 也會強制關閉應用。
所以需要注意的是,優雅關閉時一定要考慮當時的業務處理量,所設置的緩沖時間是否能處理完正在處理中的業務。
另外,Spring Boot 優雅關閉需要配合 Actuator 的 /shutdown
端點來進行觸發,具體參考這篇文章:Spring Boot 優雅停止服務的幾種方法。
好了,今天棧長就分享到了,大家可以了解學習下,對這個新特性感興趣的朋友也可以實戰測試下。
推薦去我的博客閱讀更多:
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
覺得不錯,別忘了點贊+轉發哦!