Spring Cloud Gateway重試機制原理解析
重試,我相信大家并不陌生。在我們調(diào)用Http接口的時候,總會因為某種原因調(diào)用失敗,這個時候我們可以通過重試的方式,來重新請求接口。
生活中這樣的事例很多,比如打電話,對方正在通話中啊,信號不好啊等等原因,你總會打不通,當(dāng)你第一次沒打通之后,你會打第二次,第三次…第四次就通了。
重試也要注意應(yīng)用場景,讀數(shù)據(jù)的接口比較適合重試的場景,寫數(shù)據(jù)的接口就需要注意接口的冪等性了。還有就是重試次數(shù)如果太多的話會導(dǎo)致請求量加倍,給后端造成更大的壓力,設(shè)置合理的重試機制才是最關(guān)鍵的。
今天我們來簡單的了解下Spring Cloud Gateway中的重試機制和使用。
使用講解
RetryGatewayFilter是Spring Cloud Gateway對請求重試提供的一個GatewayFilter Factory。
配置方式:
spring:
cloud:
gateway:
routes:
- id: fsh-house
uri: lb://fsh-house
predicates:
- Path=/house/**
filters:
- name: Retry
args:
retries: 3
series:
- SERVER_ERROR
statuses:
- OK
methods:
- GET
- POST
exceptions:
- java.io.IOException
配置講解
配置類源碼:org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory.RetryConfig:
public static class RetryConfig {
private int retries = 3;
private List<Series> series = toList(Series.SERVER_ERROR);
private List<HttpStatus> statuses = new ArrayList<>();
private List<HttpMethod> methods = toList(HttpMethod.GET);
private List<Class<? extends Throwable>> exceptions = toList(IOException.class);
// .....
}
retries:重試次數(shù),默認(rèn)值是3次
series:狀態(tài)碼配置(分段),符合的某段狀態(tài)碼才會進(jìn)行重試邏輯,默認(rèn)值是SERVER_ERROR,值是5,也就是5XX(5開頭的狀態(tài)碼),共有5個值:
public enum Series {
INFORMATIONAL(1),
SUCCESSFUL(2),
REDIRECTION(3),
CLIENT_ERROR(4),
SERVER_ERROR(5);
}
statuses:狀態(tài)碼配置,和series不同的是這邊是具體狀態(tài)碼的配置,取值請參考:org.springframework.http.HttpStatus
methods:指定哪些方法的請求需要進(jìn)行重試邏輯,默認(rèn)值是GET方法,取值如下:
public enum HttpMethod {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
}
exceptions:指定哪些異常需要進(jìn)行重試邏輯,默認(rèn)值是java.io.IOException
代碼測試
就寫個接口,在接口中記錄請求次數(shù),然后拋出一個異常模擬500,通過網(wǎng)關(guān)訪問這個接口,如果你配置了重試次數(shù)是3,那么接口中會輸出4次結(jié)果才是對的,證明重試生效了。
AtomicInteger ac = new AtomicInteger();
@GetMapping("/data")
public HouseInfo getData(@RequestParam("name") String name) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("error");
}
System.err.println(ac.addAndGet(1));
return new HouseInfo(1L, "上海", "虹口", "XX小區(qū)");
}
源碼欣賞
@Override
public GatewayFilter apply(RetryConfig retryConfig) {
// 驗證重試配置格式是否正確
retryConfig.validate();
Repeat<ServerWebExchange> statusCodeRepeat = null;
if (!retryConfig.getStatuses().isEmpty() || !retryConfig.getSeries().isEmpty()) {
Predicate<RepeatContext<ServerWebExchange>> repeatPredicate = context -> {
ServerWebExchange exchange = context.applicationContext();
// 判斷重試次數(shù)是否已經(jīng)達(dá)到了配置的最大值
if (exceedsMaxIterations(exchange, retryConfig)) {
return false;
}
// 獲取響應(yīng)的狀態(tài)碼
HttpStatus statusCode = exchange.getResponse().getStatusCode();
// 獲取請求方法類型
HttpMethod httpMethod = exchange.getRequest().getMethod();
// 判斷響應(yīng)狀態(tài)碼是否在配置中存在
boolean retryableStatusCode = retryConfig.getStatuses().contains(statusCode);
if (!retryableStatusCode && statusCode != null) { // null status code might mean a network exception?
// try the series
retryableStatusCode = retryConfig.getSeries().stream()
.anyMatch(series -> statusCode.series().equals(series));
}
// 判斷方法是否包含在配置中
boolean retryableMethod = retryConfig.getMethods().contains(httpMethod);
// 決定是否要進(jìn)行重試
return retryableMethod && retryableStatusCode;
};
statusCodeRepeat = Repeat.onlyIf(repeatPredicate)
.doOnRepeat(context -> reset(context.applicationContext()));
}
//TODO: support timeout, backoff, jitter, etc... in Builder
Retry<ServerWebExchange> exceptionRetry = null;
if (!retryConfig.getExceptions().isEmpty()) {
Predicate<RetryContext<ServerWebExchange>> retryContextPredicate = context -> {
if (exceedsMaxIterations(context.applicationContext(), retryConfig)) {
return false;
}
// 異常判斷
for (Class<? extends Throwable> clazz : retryConfig.getExceptions()) {
if (clazz.isInstance(context.exception())) {
return true;
}
}
return false;
};
// 使用reactor extra的retry組件
exceptionRetry = Retry.onlyIf(retryContextPredicate)
.doOnRetry(context -> reset(context.applicationContext()))
.retryMax(retryConfig.getRetries());
}
return apply(statusCodeRepeat, exceptionRetry);
}
public boolean exceedsMaxIterations(ServerWebExchange exchange, RetryConfig retryConfig) {
Integer iteration = exchange.getAttribute(RETRY_ITERATION_KEY);
//TODO: deal with null iteration
return iteration != null && iteration >= retryConfig.getRetries();
}
public void reset(ServerWebExchange exchange) {
//TODO: what else to do to reset SWE?
exchange.getAttributes().remove(ServerWebExchangeUtils.GATEWAY_ALREADY_ROUTED_ATTR);
}
public GatewayFilter apply(Repeat<ServerWebExchange> repeat, Retry<ServerWebExchange> retry) {
return (exchange, chain) -> {
if (log.isTraceEnabled()) {
log.trace("Entering retry-filter");
}
// chain.filter returns a Mono<Void>
Publisher<Void> publisher = chain.filter(exchange)
//.log("retry-filter", Level.INFO)
.doOnSuccessOrError((aVoid, throwable) -> {
// 獲取已經(jīng)重試的次數(shù),默認(rèn)值為-1
int iteration = exchange.getAttributeOrDefault(RETRY_ITERATION_KEY, -1);
// 增加重試次數(shù)
exchange.getAttributes().put(RETRY_ITERATION_KEY, iteration + 1);
});
if (retry != null) {
// retryWhen returns a Mono<Void>
// retry needs to go before repeat
publisher = ((Mono<Void>)publisher).retryWhen(retry.withApplicationContext(exchange));
}
if (repeat != null) {
// repeatWhen returns a Flux<Void>
// so this needs to be last and the variable a Publisher<Void>
publisher = ((Mono<Void>)publisher).repeatWhen(repeat.withApplicationContext(exchange));
}
return Mono.fromDirect(publisher);
};
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring Cloud Gateway + Nacos 實現(xiàn)動態(tài)路由
- Spring Cloud Gateway不同頻率限流的解決方案(每分鐘,每小時,每天)
- 詳解SpringCloudGateway內(nèi)存泄漏問題
- 基于Nacos實現(xiàn)Spring Cloud Gateway實現(xiàn)動態(tài)路由的方法
- Spring Cloud Gateway全局通用異常處理的實現(xiàn)
- spring cloud gateway整合sentinel實現(xiàn)網(wǎng)關(guān)限流
- spring cloud gateway請求跨域問題解決方案
- Springcloud GateWay網(wǎng)關(guān)配置過程圖解
相關(guān)文章
解決SpringBoot項目在啟動后自動關(guān)閉的問題
今天搭建了一個SpringBoot項目,但是在啟動之后就自行關(guān)閉了,下面通過本文給大家介紹SpringBoot項目在啟動后自動關(guān)閉問題及解決方法,需要的朋友可以參考下2023-08-08
SpringBoot實現(xiàn)第一次啟動時自動初始化數(shù)據(jù)庫的方法
本文主要介紹了SpringBoot實現(xiàn)第一次啟動時自動初始化數(shù)據(jù)庫的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
springboot-dubbo cannot be cast to問題及解決
這篇文章主要介紹了springboot-dubbo cannot be cast to問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
springboot+shiro+jwtsession和token進(jìn)行身份驗證和授權(quán)
最近和別的軟件集成項目,需要提供給別人接口來進(jìn)行數(shù)據(jù)傳輸,發(fā)現(xiàn)給他token后并不能訪問我的接口,拿postman試了下還真是不行,檢查代碼發(fā)現(xiàn)項目的shiro配置是通過session會話來校驗信息的,修改代碼兼容token和session2024-06-06

