文档章节

聊聊spring cloud gateway的RetryGatewayFilter

go4it
 go4it
发布于 06/19 23:07
字数 747
阅读 44
收藏 1

本文主要研究一下spring cloud gateway的RetryGatewayFilter

GatewayAutoConfiguration

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java

@Configuration
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore(HttpHandlerAutoConfiguration.class)
@AutoConfigureAfter({GatewayLoadBalancerClientAutoConfiguration.class, GatewayClassPathWarningAutoConfiguration.class})
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {
    //......
	@Bean
	public RetryGatewayFilterFactory retryGatewayFilterFactory() {
		return new RetryGatewayFilterFactory();
	}
    //......
}

默认启用了RetryGatewayFilterFactory

RetryGatewayFilterFactory

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/RetryGatewayFilterFactory.java

public class RetryGatewayFilterFactory extends AbstractGatewayFilterFactory<RetryGatewayFilterFactory.RetryConfig> {
	private static final Log log = LogFactory.getLog(RetryGatewayFilterFactory.class);

	public RetryGatewayFilterFactory() {
		super(RetryConfig.class);
	}

	@Override
	public GatewayFilter apply(RetryConfig retryConfig) {
		retryConfig.validate();

		Predicate<? super RepeatContext<ServerWebExchange>> predicate = context -> {
			ServerWebExchange exchange = context.applicationContext();
			if (exceedsMaxIterations(exchange, retryConfig)) {
				return false;
			}

			HttpStatus statusCode = exchange.getResponse().getStatusCode();
			HttpMethod httpMethod = exchange.getRequest().getMethod();

			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);
			return retryableMethod && retryableStatusCode;
		};

		Repeat<ServerWebExchange> repeat = Repeat.onlyIf(predicate)
				.doOnRepeat(context -> reset(context.applicationContext()));

		//TODO: support timeout, backoff, jitter, etc... in Builder

		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;
		};

		Retry<ServerWebExchange> reactorRetry = Retry.onlyIf(retryContextPredicate)
				.doOnRetry(context -> reset(context.applicationContext()))
				.retryMax(retryConfig.getRetries());
		return apply(repeat, reactorRetry);
	}

	public boolean exceedsMaxIterations(ServerWebExchange exchange, RetryConfig retryConfig) {
		Integer iteration = exchange.getAttribute("retry_iteration");

		//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);
	}

	@Deprecated
	public GatewayFilter apply(Repeat<ServerWebExchange> repeat) {
		return apply(repeat, Retry.onlyIf(ctxt -> false));
	}

	public GatewayFilter apply(Repeat<ServerWebExchange> repeat, Retry<ServerWebExchange> retry) {
		return (exchange, chain) -> {
			log.trace("Entering retry-filter");

			int iteration = exchange.getAttributeOrDefault("retry_iteration", -1);
			exchange.getAttributes().put("retry_iteration", iteration + 1);

			return Mono.fromDirect(chain.filter(exchange)
					.log("retry-filter", Level.INFO)
					.retryWhen(retry.withApplicationContext(exchange))
					.repeatWhen(repeat.withApplicationContext(exchange)));
		};
	}
    //......
}
  • 可以看到这个filter使用了reactor的Retry组件,同时往exchange的attribues添加retry_iteration,用来记录重试次数,该值默认从-1开始,第一次执行的时候,retry_iteration+1为0。之后每重试一次,就添加1。
  • filter的apply接收两个参数,一个是Repeat<ServerWebExchange>,一个是Retry<ServerWebExchange>。
  • repeat与retry的区别是repeat是在onCompleted的时候会重试,而retry是在onError的时候会重试。这里由于不一定是异常的时候才可能重试,所以加了repeat。

RetryConfig

spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/RetryGatewayFilterFactory.java

	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);

		//......

		public void validate() {
			Assert.isTrue(this.retries > 0, "retries must be greater than 0");
			Assert.isTrue(!this.series.isEmpty() || !this.statuses.isEmpty(),
					"series and status may not both be empty");
			Assert.notEmpty(this.methods, "methods may not be empty");
		}
        //......

	}

可以看到配置文件有5个属性,如下:

  • retries,默认为3,用来标识重试次数
  • series,用来指定哪些段的状态码需要重试,默认SERVER_ERROR即5xx
  • statuses,用于指定哪些状态需要重试,默认为空,它跟series至少得指定一个
  • methods,用于指定那些方法的请求需要重试,默认为GET
  • exceptions,用于指定哪些异常需要重试,默认为java.io.IOException

实例

spring:
  cloud:
    gateway:
      routes:
      - id: retry-demo
        uri: http://localhost:9090
        predicates:
        - Path=/retry/**
        filters:
        - name: Retry
          args:
           retries: 15
           series:
            - SERVER_ERROR
            - CLIENT_ERROR
           methods:
            - GET
            - POST
           exceptions:
            - java.io.IOException
            - java.util.concurrent.TimeoutException

这里指定了针对4xx及5xx的GET或POST方法或者IOException或TimeoutException的时候进行重试,重试次数为15次。

小结

RetryGatewayFilter借助了reactor-addons的retry组件进行了重试,主要使用了Mono的repeatWhen及retryWhen方法,前者在onCompleted的时候触发,后者在onError的时候触发。

doc

© 著作权归作者所有

共有 人打赏支持
go4it
粉丝 64
博文 735
码字总数 528939
作品 0
深圳
Spring Cloud Gateway重试机制

前言 重试,我相信大家并不陌生。在我们调用Http接口的时候,总会因为某种原因调用失败,这个时候我们可以通过重试的方式,来重新请求接口。 生活中这样的事例很多,比如打电话,对方正在通话...

尹吉欢
09/17
0
0
聊聊spring cloud gateway的GatewayFilter

序 本文主要研究一下spring cloud gateway的GatewayFilter GatewayFilter spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/GatewayFilter.jav......

go4it
06/09
0
0
聊聊spring.cloud.gateway.default-filters

序 本文主要研究下spring.cloud.gateway.default-filters 配置 default-filters,配置的是FilterDefinition对象 FilterDefinition spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/sp......

go4it
06/01
0
0
聊聊spring cloud的RequestHeaderToRequestUri

序 本文主要研究一下spring cloud的RequestHeaderToRequestUriGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gate......

go4it
06/16
0
0
聊聊spring cloud gateway的RedirectToGatewayFilter

序 本文主要研究下spring cloud gateway的RedirectToGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/confi......

go4it
06/13
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Redis应用之分布式锁(set)

Redis应用之分布式锁(set) 在单机应用的场景下,我们常使用的锁主要是synchronized与Lock;但是在分布式横行的大环境下,显然仅仅这两种锁已经无法满足我们的需求; 需求:秒杀场景下,有若干...

GMarshal
21分钟前
0
0
python实现简单的文件加密与解密

对于任意的一个文件,本质上来讲都是二进制的。 对于任意一个二进制数a,对其用另外任意一个与a的位数相同的二进制数m进行“异或”操作得到结果e,即e=a xor m; 如果再讲上面得到的e用m进行...

Aomo
22分钟前
0
0
Android开发应用程序生成以太坊钱包

Android应用程序以太坊钱包生成,要做的工作不少,不过如果我们一步一步来应该也比较清楚: 1.在app/build.gradle中集成以下依赖项: compile ('org.web3j:core-android:2.2.1') web3j核心是...

geek12345
37分钟前
0
0
ArrayList嘿嘿嘿

数组扩容技术: //扩容技术 将原数组objs类容复制到新数组并且长度为11 Object[] newObjs = Arrays.copyOf(objs,11); 数组比较大那么System.arraycopy比较有优势,因为其使用的是内存复制,省...

熊猫你好
今天
2
0
Android平台下的一个好用的日历库(sxtwl_cpp),支持农历转公历,和公历转农历等功能

python版的sxtwl_cpp传送入口 在build.gradle的allprojects中加入 maven { url 'https://dl.bintray.com/yuangu/sxtwl' } 最终如下面代码所示: allprojects { repositories { ......

元谷
今天
18
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部