
本文详解 resilience4j 各核心注解(@bulkhead、@timelimiter、@circuitbreaker、@retry)的嵌套执行顺序,结合 completablefuture 场景说明异常传播路径,并指导如何通过 retryexceptions、ignoreexceptions 和自定义 predicate 实现“仅对服务端异常重试”的精准控制。
本文详解 resilience4j 各核心注解(@bulkhead、@timelimiter、@circuitbreaker、@retry)的嵌套执行顺序,结合 completablefuture 场景说明异常传播路径,并指导如何通过 retryexceptions、ignoreexceptions 和自定义 predicate 实现“仅对服务端异常重试”的精准控制。
Resilience4j 的 AOP 增强采用由外向内、层层包裹的执行模型,其实际调用链严格遵循以下嵌套顺序(从最外层到最内层):
@Retry
→ @CircuitBreaker
→ @TimeLimiter
→ @Bulkhead
→ 目标方法(downstream1)这意味着:当方法被调用时,首先由 @Retry 拦截;若需重试,则整个内部链(断路器→超时→舱壁→业务逻辑)将被重复执行。而异常则按逆序向上抛出:目标方法抛出异常 → 舱壁捕获并可能包装为 BulkheadFullException → 超时装饰器捕获并转为 TimeoutException → 断路器检查状态并可能抛 CallNotPermittedException → 最终由 @Retry 决定是否重试。
你对各异常场景的理解基本正确,但需特别注意一个关键细节:@Retry 默认会对所有非受检异常(unchecked exceptions)重试,包括 TimeoutException、CallNotPermittedException 等——这与你的业务诉求(仅对下游服务端错误,如 5xx HTTP 异常重试)相悖。因此,必须显式配置重试过滤策略。
✅ 正确配置方式(推荐组合)
在 application.yml(而非 .properties,更清晰支持嵌套结构)中配置如下:
resilience4j.retry:
configs:
default:
max-attempts: 3
wait-duration: 100ms
# ✅ 只对服务端错误重试(如 5xx)
retry-exceptions:
- org.springframework.web.client.HttpServerErrorException
- java.net.SocketTimeoutException
- java.io.IOException
# ✅ 明确排除不应重试的异常(优先级高于 retry-exceptions)
ignore-exceptions:
- io.github.resilience4j.bulkhead.BulkheadFullException
- java.util.concurrent.TimeoutException
- io.github.resilience4j.circuitbreaker.CallNotPermittedException
- org.springframework.web.client.HttpClientErrorException # 客户端错误(4xx),不重试⚠️ 注意:ignore-exceptions 的匹配优先级高于 retry-exceptions,且一旦命中即跳过重试,直接进入 fallback。
? 进阶:基于响应结果的动态重试(可选)
若需更精细控制(例如:HTTP 200 响应但 body 中 status: "FAILED"),可实现 RetryOnResultPredicate:
@Component
public class ShouldRetryOnHttpStatus implements Predicate<HttpResponse> {
@Override
public boolean test(HttpResponse response) {
return response != null
&& response.getStatusCode() >= 500
&& response.getStatusCode() < 600;
}
}并在配置中启用:
resilience4j.retry.instances.downstream1: base-config: default retry-on-result-predicate: com.example.predicates.ShouldRetryOnHttpStatus
? 重要注意事项
- @TimeLimiter + CompletableFuture 是必需组合:你当前代码使用 CompletableFuture 并标注 @TimeLimiter 是正确的;若返回普通 String,则 @TimeLimiter 将无效(无异步上下文)。
- Fallback 方法签名必须兼容所有可能异常类型:你的 downstream1Fallback(String a, Exception e) 已满足要求,能接收各类包装异常。
- 线程池 Bulkhead 与 TimeLimiter 协同:@Bulkhead(type = THREADPOOL) 会提交任务到独立线程池,@TimeLimiter 在该线程内启动超时监控,二者不冲突。
- 避免配置冗余:resilience4j.retry.instances.downstream1.max-attempts=1 在生产环境通常无意义,建议设为 3 并配合指数退避(enable-exponential-backoff: true)。
✅ 总结
你的执行顺序理解准确,但默认重试行为不符合业务目标。无需修改执行顺序(也无法修改),而应通过 ignore-exceptions 精确屏蔽 BulkheadFullException、TimeoutException、CallNotPermittedException 等非服务端异常,再辅以 retry-exceptions 明确限定重试范围。此方案零侵入、高可维护,完全契合“仅对服务端异常重试”的核心诉求。

















