Spring 6与Spring Boot 3中新HTTP接口的重试实现方法
Spring新HTTP接口整合重试机制
Spring的声明式HTTP接口(基于WebClient)整合重试逻辑,可通过以下几种方式实现:
1. 全局配置重试(基于WebClient过滤器)
在构建WebClient时添加ExchangeFilterFunction,统一处理所有请求的重试逻辑,同时结合状态处理器捕获错误响应:
WebClient webClient = WebClient.builder() // 全局重试逻辑:针对错误响应或IO异常重试3次,间隔2秒 .filter((request, next) -> next.exchange(request) .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)) .filter(t -> t instanceof WebClientResponseException || t instanceof IOException))) // 错误状态处理器:将错误响应转为异常,供重试逻辑捕获 .defaultStatusHandler(HttpStatusCode::isError, resp -> Mono.error(new WebClientResponseException( resp.statusCode().value(), resp.statusCode().getReasonPhrase(), resp.headers().asHttpHeaders(), null, null, null))) .build(); // 用配置好的WebClient创建声明式HTTP接口实例 MyHttpInterface httpInterface = WebClientHttpConnectorAdapter.forClient(webClient) .createClient(MyHttpInterface.class);
2. 单个接口方法单独配置重试
若只需给特定接口方法添加重试,可在调用方法时直接对返回的Mono/Flux添加重试逻辑:
首先定义声明式接口:
public interface MyHttpInterface { @GetExchange("/path/{stockId}") Mono<String> getData(@PathVariable String stockId); }
调用时包装重试:
public Mono<String> fetchDataWithRetry(String stockId) { return httpInterface.getData(stockId) .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)) .filter(t -> t instanceof WebClientResponseException)); }
3. 结合Spring Retry注解实现
如果习惯使用Spring Retry的注解方式,需先启用重试配置:
@Configuration @EnableRetry public class RetryConfiguration { @Bean public RetryTemplate retryTemplate() { RetryTemplate retryTemplate = new RetryTemplate(); // 配置固定间隔退避策略 FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy(); backOffPolicy.setBackOffPeriod(2000); retryTemplate.setBackOffPolicy(backOffPolicy); // 配置重试次数 SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(3); retryTemplate.setRetryPolicy(retryPolicy); return retryTemplate; } }
随后在声明式接口方法上添加@Retryable注解:
public interface MyHttpInterface { @GetExchange("/path/{stockId}") @Retryable(value = {WebClientResponseException.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000)) Mono<String> getData(@PathVariable String stockId); }
注意:Spring Retry已支持反应式类型(Mono/Flux)的重试处理,无需额外适配。
内容的提问来源于stack exchange,提问作者pooya72
相关产品推荐
相关产品推荐

