我可以添加多个retryWhen
来执行重试以处理不同的 WebClient 故障响应吗?
我想要达到的目标:
我正在使用 WebClient 进行 REST API 调用。很少有错误场景,发生时我需要执行重试,但延迟不同。
例如,1.如果401 Unauthorize
发生,我可以在刷新令牌后立即重试。2. 如果502/503 Server
发生错误,我需要延迟 5 秒后重试。3.如果429 Too Many Request
发生,我需要延迟重试时间,比如20秒后。
我想创建如下重试规范:
protected static final Predicate<Throwable> is401 =
(throwable) -> throwable instanceof WebClientResponseException.Unauthorized;
protected static final Predicate<Throwable> is5xx =
(throwable) -> throwable instanceof WebClientResponseException.ServiceUnavailable;
protected static final Predicate<Throwable> is429 =
(throwable) -> throwable instanceof WebClientResponseException.TooManyRequests;
Retry retry401 = Retry.fixedDelay(5, Duration.ofSeconds(1))
.filter(is401)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());
Retry retry5xx = Retry.fixedDelay(5, Duration.ofSeconds(10))
.filter(is5xx)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());
Retry retry429 = Retry.fixedDelay(5, Duration.ofSeconds(20))
.filter(is429)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());
// trying to apply the to WebClient like below:
WebClient.Builder()
.get()
.uri("endpointuri")
.retrieve()
.bodyToFlux(String.class)
.retryWhen(retry401)
.retryWhen(retry5xx)
.retryWhen(retry429);
看起来 `.retryWhen(retry429)' 会覆盖其他重试。