spring webclient:重试特定错误时退避

pio*_*rek 14 java spring project-reactor spring-webflux spring-webclient

当响应为 5xx 时,我想在等待 10 秒后重试请求 3 次。但我没有看到可以使用的方法。在对象上

WebClient.builder()
                .baseUrl("...").build().post()
                .retrieve().bodyToMono(...)
Run Code Online (Sandbox Code Playgroud)

我可以看到方法:

在重试次数但没有延迟的条件下重试

.retry(3, {it is WebClientResponseException && it.statusCode.is5xxServerError} )
Run Code Online (Sandbox Code Playgroud)

重试退避和次数但没有条件

.retryBackoff 
Run Code Online (Sandbox Code Playgroud)

还有一个,retryWhen但我不知道如何使用它

Ale*_*kin 19

使用 reactor-extra 你可以这样做:

.retryWhen(Retry.onlyIf(this::is5xxServerError)
        .fixedBackoff(Duration.ofSeconds(10))
        .retryMax(3))

private boolean is5xxServerError(RetryContext<Object> retryContext) {
    return retryContext.exception() instanceof WebClientResponseException &&
            ((WebClientResponseException) retryContext.exception()).getStatusCode().is5xxServerError();
}
Run Code Online (Sandbox Code Playgroud)

更新: 使用新 API,相同的解决方案将是:

    .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(10))
            .filter(this::is5xxServerError));

//...

private boolean is5xxServerError(Throwable throwable) {
    return throwable instanceof WebClientResponseException &&
            ((WebClientResponseException) throwable).getStatusCode().is5xxServerError();
}
Run Code Online (Sandbox Code Playgroud)


Sud*_*.R. 8

我认为 retryWhen 与 Retry.anyOf 和 Retry.onlyIf 已被弃用。我发现这种方法很有用,它允许我们处理和抛出用户定义的异常。

例如 :

retryWhen(Retry.backoff(3, Duration.of(2, ChronoUnit.SECONDS))
                        .filter(error -> error instanceof UserDefinedException/AnyOtherException)
                        .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) ->
                                new UserDefinedException(retrySignal.failure().getMessage())))
Run Code Online (Sandbox Code Playgroud)


Mic*_*rry 7

您可以采用以下方法执行此操作:

  • 使用exchange()方法获取无异常的响应,然后在 5xx 响应上抛出一个特定的(自定义)异常(这与retrieve()总是WebClientResponseException以 a4xx或5xxstatus抛出的不同);
  • 在您的重试逻辑中拦截此特定异常;
  • 使用reactor-extra- 它包含一种retryWhen()用于更复杂和特定重试的好方法。然后,您可以指定随机退避重试,该重试在 10 秒后开始,增加到任意时间并最多尝试 3 次。(当然,您也可以使用其他可用方法来选择不同的策略。)

例如:

//...webclient
.exchange()
.flatMap(clientResponse -> {
    if (clientResponse.statusCode().is5xxServerError()) {
        return Mono.error(new ServerErrorException());
    } else {
        //Any further processing
    }
}).retryWhen(
    Retry.anyOf(ServerErrorException.class)
       .randomBackoff(Duration.ofSeconds(10), Duration.ofHours(1))
       .maxRetries(3)
    )
);
Run Code Online (Sandbox Code Playgroud)