如何为Reactor HttpClient配置重试策略并供所有WebClient调用共享?
统一配置WebClient全局重试策略
可以在reactor.netty.http.client.HttpClient层面统一设置重试策略,再基于该HttpClient构建WebClient,这样所有通过此WebClient发起的请求都会自动应用同一重试逻辑,无需在每个请求方法中重复编写retryWhen代码。
实现步骤
1. 配置带全局重试策略的HttpClient
使用Reactor Netty的HttpClient的retry()方法,传入预定义的重试规则,完全匹配你需求的逻辑:3次退避重试、间隔1秒、仅针对5xx服务器错误重试。
import reactor.netty.http.client.HttpClient; import reactor.util.retry.Retry; import org.springframework.web.reactive.function.client.WebClientResponseException; import java.io.IOException; import java.time.Duration; // 定义全局重试策略 Retry globalRetry = Retry.backoff(3, Duration.ofSeconds(1)) .filter(throwable -> { // 过滤5xx服务器错误 if (throwable instanceof WebClientResponseException) { WebClientResponseException ex = (WebClientResponseException) throwable; return ex.getStatusCode().is5xxServerError(); } // 可选:额外处理连接超时、连接失败等底层IO异常 return throwable instanceof IOException; }); // 绑定重试策略到HttpClient HttpClient httpClient = HttpClient.create() .retry(globalRetry);
2. 基于配置好的HttpClient创建WebClient
将上述HttpClient传入WebClient构建器,后续所有请求都会自动继承全局重试规则:
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.http.client.reactive.ReactorClientHttpConnector; WebClient webClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .baseUrl("your-base-api-url") .build();
3. 简化后的请求方法
现在调用WebClient时无需再手动添加retryWhen,全局策略会自动生效:
public ModelResponse exampleMethod() { return webClient .get() .uri("/example") .retrieve() .bodyToMono(ModelResponse.class) .block(); }
注意事项
- HttpClient层面的重试触发于底层HTTP通信阶段,不仅覆盖WebClient响应阶段的5xx错误,还能处理连接超时、连接失败等底层IO异常(可通过
filter调整过滤规则)。 - 如果某特定请求需要覆盖全局策略,可在该请求的Mono/Flux链上再次添加
retryWhen,局部策略会优先生效。
内容的提问来源于stack exchange,提问作者Tchorzyksen
相关产品推荐
相关产品推荐

