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