
本文介绍如何在 Spring WebFlux 中基于 WebClient 实现灵活、可配置的多级重试机制,支持从 application.yml 读取不同延迟时间(如 1s、3s、10s…),并在每次重试时按序应用对应延迟,而非固定间隔。
本文介绍如何在 spring webflux 中基于 `webclient` 实现灵活、可配置的多级重试机制,支持从 `application.yml` 读取不同延迟时间(如 1s、3s、10s…),并在每次重试时按序应用对应延迟,而非固定间隔。
在 Spring WebFlux 中,Retry.backoff() 默认仅支持固定基数(如指数退避)或固定延迟,但无法直接满足「按预定义序列逐级切换延迟时间」的需求——例如依次使用 [1, 3, 10, 30, 120, 200, 360, 450](单位:秒)作为每次重试的等待时长。此时需放弃默认 backoff(int, Duration),转而使用更底层的 Retry.from(Iterable<retryspec>)</retryspec> 或自定义 RetrySpec 生成逻辑。
✅ 正确方案:使用 Retry.from() + 动态延迟序列
首先,在 application.yml 中定义可配置的延迟数组:
app:
retry:
delays-seconds: [1, 3, 10, 30, 120, 200, 360, 450]然后在配置类中注入并构建重试策略:
@Configuration
public class WebClientConfig {
@Value("${app.retry.delays-seconds}")
private List<Long> retryDelaysSeconds;
@Bean
public WebClient webClient() {
return WebClient.builder()
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
.build();
}
// 构建支持逐级自定义延迟的 Retry 实例
public Retry buildCustomRetry() {
return Retry.from(
Flux.fromIterable(retryDelaysSeconds)
.map(seconds -> RetrySpec.max(1) // 每个延迟只触发一次重试
.fixedDelay(Duration.ofSeconds(seconds))
.onRetryExhaustedThrow((spec, signal) -> {
// 所有延迟尝试完毕后抛出最终异常
return signal.getThrowable();
})
)
);
}
}在业务逻辑中使用该重试策略:
@Service
public class StudentService {
private final WebClient webClient;
private final Retry customRetry;
public StudentService(WebClient webClient, WebClientConfig config) {
this.webClient = webClient;
this.customRetry = config.buildCustomRetry();
}
public Mono<List<Student>> fetchStudentsWithSequentialRetry() {
return webClient.get()
.uri("https://api.example.com/students")
.retrieve()
.bodyToFlux(Student.class)
.collectList()
.retryWhen(customRetry)
.onErrorResume(e -> {
log.error("All retry attempts exhausted for student fetch", e);
return Mono.empty(); // 或抛出自定义业务异常
});
}
}⚠️ 注意事项与最佳实践
- 延迟数组长度即最大重试次数:若配置了 8 个延迟值,则最多重试 8 次(首次请求 + 8 次重试 = 9 次总调用);
-
空响应/5xx 均需显式触发重试:
retryWhen()默认仅对Mono.error()响应生效;若服务返回null或空Flux,需配合switchIfEmpty(Mono.error(...))或handle()显式抛出异常; -
避免阻塞式延迟:切勿在
retryWhen中使用Thread.sleep()或Mono.delay().block(),这将破坏响应式流的非阻塞特性; -
可观测性增强:建议通过
doOnRetry()记录每次重试的延迟值和原因:
.retryWhen(Retry.from(Flux.fromIterable(retryDelaysSeconds)
.map(sec -> RetrySpec.max(1)
.fixedDelay(Duration.ofSeconds(sec))
.doOnRetry(context ->
log.info("Retrying #{} after {}s delay. Reason: {}",
context.iteration(), sec, context.exception().getMessage())
)
)
))通过该方案,你完全掌控每次重试的延迟节奏,既符合运维可配置需求,又保持响应式编程模型的高效与弹性。


















