Spring WebClient:在发生特定错误时重试并退避 [英] spring webclient: retry with backoff on specific error

查看:51
本文介绍了Spring WebClient:在发生特定错误时重试并退避的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在响应为5xx时等待10秒后重试该请求3次.但我看不到可以使用的方法.在物体上

i'd like to retry the request 3 times after waiting 10sec when response is 5xx. but i don't see a method that I can use. On object

WebClient.builder()
                .baseUrl("...").build().post()
                .retrieve().bodyToMono(...)

我可以看到方法:

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

retrying on condition with retry count but no delay

.retry(3, {it is WebClientResponseException && it.statusCode.is5xxServerError} )

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

retrying with backoff and number of times but no condition

.retryBackoff 

还有一个 retryWhen ,但是我不确定如何使用

there is also a retryWhen but i'm not sure how to use it

推荐答案

使用Reactor-extra,您可以这样做:

With reactor-extra you could do it like:

.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();
}

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

Update: With new API the same solution will be:

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

//...

private boolean is5xxServerError(Throwable throwable) {
    return throwable instanceof WebClientResponseException &&
            ((WebClientResponseException) throwable).getStatusCode().is5xxServerError();
}

这篇关于Spring WebClient:在发生特定错误时重试并退避的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆