Spring Boot(Cloud) 優(yōu)雅停機(jī)
為了解決在微服務(wù)重啟的過程中,可能出現(xiàn)一部分 http 請(qǐng)求處理失敗的問題,提供一下方案
擬用方案:
第一步:重啟前先從主動(dòng)將服務(wù)剔除,并等待一段時(shí)間
第二步:停止服務(wù)并重啟
該方案主要考慮因?yàn)榉?wù)下線的瞬間,如果服務(wù)信息更新不及時(shí),導(dǎo)致復(fù)雜均衡算法依然轉(zhuǎn)發(fā)到已經(jīng)停掉的實(shí)例上發(fā)生一些服務(wù)不可用的情況
在每個(gè)項(xiàng)目增加一個(gè)接口(例如 /discovery/deregister ),在項(xiàng)目重啟的腳本中主動(dòng)調(diào)用接口剔除這個(gè)服務(wù),shell 大致改動(dòng)如下:
function?stop()
{????
????echo?"deregister?[${PROJECT}]."
????curl?-X?POST?"127.0.0.1:${SERVER_PORT}/discovery/deregister"
????echo?""
????echo?"deregister?[${PROJECT}]?then?sleep?10?seconds."
????sleep?10
????kill?xxxxxxxxxxxxxxxxxxxx
}
接口代碼示例
import?lombok.extern.slf4j.Slf4j;
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.cloud.client.serviceregistry.Registration;
import?org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import?org.springframework.context.annotation.Lazy;
import?org.springframework.web.bind.annotation.PostMapping;
import?org.springframework.web.bind.annotation.RequestMapping;
import?org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("discovery")
@Slf4j
public?class?DeregisterInstanceController?{
??@Autowired
??@Lazy
??private?ServiceRegistry?serviceRegistry;
??@Autowired
??@Lazy
??private?Registration?registration;
??@PostMapping("deregister")
??public?void?deregister()?{
????log.info("deregister?serviceName:{},?ip:{},?port:{}",
????????registration.getServiceId(),
????????registration.getHost(),
????????registration.getPort());
????try?{
??????serviceRegistry.deregister(registration);
????}?catch?(Exception?e)?{
??????log.error("deregister?error",?e);
????}
??}
}
二、Spring Boot 自帶的優(yōu)雅停機(jī)方案要求 Spring Boot 的版本大于等于 2.3
在配置文件中增加如下配置:
application.yaml
server:
????shutdown:?graceful
spring:
????lifecycle:
????????timeout-per-shutdown-phase:?10s
當(dāng)使用 server.shutdown=graceful啟用時(shí),在 Web 容器關(guān)閉時(shí),Web 服務(wù)器將不再接收新請(qǐng)求,并將等待活動(dòng)請(qǐng)求完成的緩沖期。緩沖器默認(rèn)是 30s, 具體項(xiàng)目時(shí)間根據(jù)具體情況而定
不同 web 容器優(yōu)雅停機(jī)行為區(qū)別
容器停機(jī)行為取決于具體的 web 容器行為
| web 容器名稱 | 行為說明 |
|---|---|
| tomcat 9.0.33+ | 停止接收請(qǐng)求,客戶端新請(qǐng)求等待超時(shí)。 |
| Reactor Netty | 停止接收請(qǐng)求,客戶端新請(qǐng)求等待超時(shí)。 |
| Undertow | 停止接收請(qǐng)求,客戶端新請(qǐng)求直接返回 503。 |
兩者一同使用效果更加
評(píng)論
圖片
表情
