You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot升级后RestService中Retry功能失效无法调用anyOf等方法求助

问题根因

Spring Boot 2.5.4 内置的 Reactor Core 版本升级至 3.4.x 系列,原属于 reactor-extra 组件的重试API被正式整合到 Reactor Core 中,原有 Retry.anyOf()、retryMax()、实例级 exponentialBackoff() 等旧API全部被重构废弃,因此会出现方法找不到的报错。

新版重试API正确实现

重试规则定义代码

import reactor.util.retry.Retry;
import java.time.Duration;

public class RestService {

    private final LoggingPropertyWriter loggingPropertyWriter;
    private final WebClient webClient;
    private Retry exponentialRetrySpecification;

    public RestService(LoggingPropertyWriter loggingPropertyWriter,
                       WebClient webClient,
                       long firstBackoffMs,
                       long maxBackoffMs,
                       long maxRetryIterations) {

        this.loggingPropertyWriter = loggingPropertyWriter;
        this.webClient = webClient;
        // 新版Reactor Retry实现
        this.exponentialRetrySpecification =
                // 第一个参数是最大重试次数,第二个是初始退避间隔
                Retry.backoff(maxRetryIterations, Duration.ofMillis(firstBackoffMs))
                        // 最大退避时间设置
                        .maxBackoff(Duration.ofMillis(maxBackoffMs))
                        // 仅重试指定异常
                        .filter(throwable -> throwable instanceof PacmanHttpResponseRetryException)
                        // 重试前的回调逻辑
                        .doBeforeRetry(retrySignal -> {
                            PacmanHttpResponseRetryException retryEx = (PacmanHttpResponseRetryException) retrySignal.failure();
                            log.info(() -> LoggingContentCreator.logHttpRetry(
                                    retrySignal.totalRetries() + 1, // 次数从0开始计数,+1对应原有iteration语义
                                    retryEx.getMessage(),
                                    retryEx.getErrorCategory(),
                                    retryEx.getResponse()
                            ));
                        });
    }
}

WebClient调用时的重试触发代码

// WebClient调用时添加重试逻辑示例
webClient.get()
        .uri("/your-api-path")
        .retrieve()
        .bodyToMono(String.class)
        // 重试直接传入上面定义好的Retry实例即可
        .retryWhen(exponentialRetrySpecification)
        .subscribe();

兼容说明

如果暂时不想调整现有代码逻辑,可手动在Gradle中引入兼容旧API的reactor-extra依赖,但该方案属于过渡方案,后续版本旧API会被彻底移除,建议优先使用Core模块的新版重试API。

// build.gradle 依赖配置示例
implementation 'io.projectreactor.addons:reactor-extra:3.4.9'

常见检查项

  • 执行gradle dependencies | grep reactor确认所有Reactor相关依赖版本统一,避免多版本冲突导致类加载异常
  • 确认Retry的导入包为reactor.util.retry.Retry,而非旧版的reactor.retry.Retry

内容的提问来源于stack exchange,提问作者pk87

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:09:01