Spring Cloud Gateway重試機(jī)制的實(shí)現(xiàn)
前言
重試,我相信大家并不陌生。在我們調(diào)用Http接口的時(shí)候,總會(huì)因?yàn)槟撤N原因調(diào)用失敗,這個(gè)時(shí)候我們可以通過(guò)重試的方式,來(lái)重新請(qǐng)求接口。
生活中這樣的事例很多,比如打電話(huà),對(duì)方正在通話(huà)中啊,信號(hào)不好啊等等原因,你總會(huì)打不通,當(dāng)你第一次沒(méi)打通之后,你會(huì)打第二次,第三次...第四次就通了。
重試也要注意應(yīng)用場(chǎng)景,讀數(shù)據(jù)的接口比較適合重試的場(chǎng)景,寫(xiě)數(shù)據(jù)的接口就需要注意接口的冪等性了。還有就是重試次數(shù)如果太多的話(huà)會(huì)導(dǎo)致請(qǐng)求量加倍,給后端造成更大的壓力,設(shè)置合理的重試機(jī)制才是最關(guān)鍵的。
今天我們來(lái)簡(jiǎn)單的了解下Spring Cloud Gateway中的重試機(jī)制和使用。
使用講解
RetryGatewayFilter是Spring Cloud Gateway對(duì)請(qǐng)求重試提供的一個(gè)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
配置講解
配置類(lèi)源碼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)碼才會(huì)進(jìn)行重試邏輯,默認(rèn)值是SERVER_ERROR,值是5,也就是5XX(5開(kāi)頭的狀態(tài)碼),共有5個(gè)值:
public enum Series { INFORMATIONAL(1), SUCCESSFUL(2), REDIRECTION(3), CLIENT_ERROR(4), SERVER_ERROR(5); }
statuses:狀態(tài)碼配置,和series不同的是這邊是具體狀態(tài)碼的配置,取值請(qǐng)參考:org.springframework.http.HttpStatus
methods:指定哪些方法的請(qǐng)求需要進(jìn)行重試邏輯,默認(rèn)值是GET方法,取值如下:
public enum HttpMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; }
exceptions:指定哪些異常需要進(jìn)行重試邏輯,默認(rèn)值是java.io.IOException
代碼測(cè)試
就寫(xiě)個(gè)接口,在接口中記錄請(qǐng)求次數(shù),然后拋出一個(gè)異常模擬500,通過(guò)網(wǎng)關(guān)訪(fǎng)問(wèn)這個(gè)接口,如果你配置了重試次數(shù)是3,那么接口中會(huì)輸出4次結(jié)果才是對(duì)的,證明重試生效了。
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ū)"); }
更多Spring Cloud代碼盡在:https://github.com/yinjihuan/spring-cloud
源碼欣賞
@Override public GatewayFilter apply(RetryConfig retryConfig) { // 驗(yàn)證重試配置格式是否正確 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(); // 獲取請(qǐng)求方法類(lèi)型 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); }; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringCloud Gateway跨域配置代碼實(shí)例
- 創(chuàng)建網(wǎng)關(guān)項(xiàng)目(Spring Cloud Gateway)過(guò)程詳解
- Spring Cloud Gateway 服務(wù)網(wǎng)關(guān)快速實(shí)現(xiàn)解析
- springboot2.0和springcloud Finchley版項(xiàng)目搭建(包含eureka,gateWay,F(xiàn)reign,Hystrix)
- 詳解Spring Cloud Gateway基于服務(wù)發(fā)現(xiàn)的默認(rèn)路由規(guī)則
- Spring Cloud GateWay 路由轉(zhuǎn)發(fā)規(guī)則介紹詳解
- 阿里Sentinel支持Spring Cloud Gateway的實(shí)現(xiàn)
- springcloud gateway聚合swagger2的方法示例
- spring cloud gateway 全局過(guò)濾器的實(shí)現(xiàn)
- spring cloud gateway整合sentinel實(shí)現(xiàn)網(wǎng)關(guān)限流
相關(guān)文章
Spring Boot 2.4配置特定環(huán)境時(shí)spring: profiles提示被棄用的原
這篇文章主要介紹了Spring Boot 2.4配置特定環(huán)境時(shí)spring: profiles提示被棄用的原因,本文給大家分享詳細(xì)解決方案,需要的朋友可以參考下2023-04-04Java實(shí)現(xiàn)網(wǎng)絡(luò)數(shù)據(jù)提取所需知識(shí)點(diǎn)
這篇文章主要介紹了Java實(shí)現(xiàn)網(wǎng)絡(luò)數(shù)據(jù)提取所需知識(shí)點(diǎn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07詳解Java中Dijkstra(迪杰斯特拉)算法的圖解與實(shí)現(xiàn)
Dijkstra(迪杰斯特拉)算法是典型的單源最短路徑算法,用于計(jì)算一個(gè)節(jié)點(diǎn)到其他所有節(jié)點(diǎn)的最短路徑。本文將詳解該算法的圖解與實(shí)現(xiàn),需要的可以參考一下2022-05-05使用jpa之動(dòng)態(tài)插入與修改(重寫(xiě)save)
這篇文章主要介紹了使用jpa之動(dòng)態(tài)插入與修改(重寫(xiě)save),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11解決springcloud-eureka注冊(cè)時(shí)的ip問(wèn)題
這篇文章主要介紹了解決springcloud-eureka注冊(cè)時(shí)的ip問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08一篇文章帶你了解Maven的坐標(biāo)概念以及依賴(lài)管理
這篇文章主要為大家介紹了Maven的坐標(biāo)概念以及依賴(lài)管理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01JavaMail整合Spring實(shí)現(xiàn)郵件發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了JavaMail整合Spring實(shí)現(xiàn)郵件發(fā)送功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08Spring Cloud構(gòu)建Eureka應(yīng)用的方法
這篇文章主要介紹了Spring Cloud構(gòu)建Eureka應(yīng)用的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03Springmvc數(shù)據(jù)格式化原理及代碼案例
這篇文章主要介紹了Springmvc數(shù)據(jù)格式化原理及代碼案例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10如何利用Java8 Stream API對(duì)Map按鍵或值排序
這篇文章主要給大家介紹了關(guān)于如何利用Java8 Stream API對(duì)Map按鍵或值排序的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Java8具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11