[轉(zhuǎn)]Nginx主動(dòng)式后端服務(wù)器健康檢查配置
環(huán)境:
SpringCloud微服務(wù)(eureka注冊(cè)中心);
nginx作為負(fù)載均衡;
場(chǎng)景:
Nginx -> A服務(wù)
當(dāng)流量高峰期時(shí),kill A服務(wù)
A服務(wù)還沒(méi)有掛掉,但是注冊(cè)中心狀態(tài)為OUT_OF_SERVICE,但是服務(wù)在Nginx的upstream中。
Nginx的流量還是會(huì)到達(dá)A服務(wù),但是A服務(wù)Fegin接口調(diào)用其他服務(wù)時(shí),會(huì)出現(xiàn)異常情況。
解決方案:
Nginx主動(dòng)式調(diào)用服務(wù)器端的接口(自定義的監(jiān)控檢查接口)。
自定義檢查接口:查詢(xún)Eureka的狀態(tài),若狀態(tài)不是up狀態(tài),那么返回500異常。
Nginx收到500異常后,自動(dòng)將ip:port在upstream中摘除。
代碼實(shí)現(xiàn):
@RestController
@Slf4j
public class HealthController {
@Autowired
private EurekaClient eurekaClient;
@RequestMapping(value = "/health/check/status", method = {RequestMethod.HEAD, RequestMethod.GET})
public boolean checkStatus(HttpServletResponse response) {
try {
InstanceInfo.InstanceStatus instanceRemoteStatus = eurekaClient.getInstanceRemoteStatus();
boolean up = InstanceInfo.InstanceStatus.UP.equals(instanceRemoteStatus);
//設(shè)置http的響應(yīng)碼
if (!up) {
response.setStatus(500);
}
return up;
} catch (Exception e) {
return true;
}
}
}
Nginx配置:
upstream student-service-api {
server 172.26.34.101:9050;
check interval=3000 rise=2 fall=5 timeout=1000 type=http;
check_http_send "HEAD /health/check/status HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
- interval表示每隔3000毫秒向后端發(fā)送健康檢查包;
- rise表示如果連續(xù)成功次數(shù)達(dá)到2 服務(wù)器就被認(rèn)為是up;
- fail表示如果連續(xù)失敗次數(shù)達(dá)到5 服務(wù)器就被認(rèn)為是down;
- timeout表示后端健康請(qǐng)求的超時(shí)時(shí)間是1000毫秒;
- type表示發(fā)送的健康檢查包是http請(qǐng)求;
- check_http_send 表示http健康檢查包發(fā)送的請(qǐng)求內(nèi)容。為了減少傳輸數(shù)據(jù)量,推薦采用“head”方法;
- check_http_expect_alive 指定HTTP回復(fù)的成功狀態(tài),默認(rèn)認(rèn)為2XX和3XX的狀態(tài)是健康的;
配置location,查看服務(wù)器的健康狀態(tài)
location ~* /status {
check_status;
access_log off;
}
原文:https://www.jianshu.com/p/beb9d8d26464
參考:Nginx實(shí)戰(zhàn)系列之功能篇----后端節(jié)點(diǎn)健康檢查

浙公網(wǎng)安備 33010602011771號(hào)