Resilience4j 实现“特定异常触发降级+熔断”需配置 CircuitBreaker 的 recordExceptions/ignoreExceptions,并用 Decorators 链式组合 circuitBreaker 与 fallback;fallback 仅在 recordExceptions 异常导致失败或熔断器为 OPEN 状态时执行。

Resilience4j 在 Java 中实现“触发特定异常时降级 + 熔断”,核心是组合使用 CircuitBreaker 和 Fallback,并通过配置让熔断器只对指定异常敏感,再在执行失败时自动走降级逻辑。
1. 配置熔断器只对特定异常开启熔断
默认情况下,Resilience4j 的熔断器会对所有 Throwable 做统计(包括受检异常),但你可通过 recordExceptions 明确指定哪些异常触发失败计数,其他异常不计入熔断判断。
例如:只让 TimeoutException 和自定义的 ServiceUnavailableException 触发熔断,而 IllegalArgumentException 不影响状态:
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // 失败率超50%开启熔断
.waitDurationInOpenState(Duration.ofSeconds(60))
.permittedNumberOfCallsInHalfOpenState(10)
.recordExceptions(TimeoutException.class, ServiceUnavailableException.class)
.ignoreExceptions(IllegalArgumentException.class) // 完全忽略这类异常
.build();
2. 使用装饰器链:CircuitBreaker + Fallback
Resilience4j 不像 Hystrix 那样内置“熔断即降级”,它把熔断、重试、降级拆成独立组件。你需要手动将 fallback 逻辑绑定到被熔断/失败的调用上,推荐用 Decorators 链式包装:
立即学习“Java免费学习笔记(深入)”;
- 用
Decorators.ofSupplier(...)包裹业务逻辑 Supplier - 用
.withCircuitBreaker(circuitBreaker)加入熔断控制 - 用
.withFallback((throwable) -> {...})定义降级返回值(注意:fallback 函数必须返回与原 Supplier 相同类型)
示例:
CircuitBreaker circuitBreaker = CircuitBreaker.of("myService", config);
Supplier<String> decoratedSupplier = Decorators.ofSupplier(() -> {
// 模拟可能抛出 TimeoutException 或 ServiceUnavailableException 的远程调用
if (Math.random() > 0.8) throw new TimeoutException("timeout");
return "success";
})
.withCircuitBreaker(circuitBreaker)
.withFallback(throwable -> {
// 这里只会在 circuitBreaker 认定为“失败”(即 recordExceptions 中的异常)或熔断开启时被调用
// 注意:IllegalArgumentException 不会进这里(因被 ignoreExceptions 排除)
log.warn("Fallback triggered for {}", throwable.getClass().getSimpleName());
return "default_value_from_cache_or_stub";
});
String result = decoratedSupplier.get(); // 自动触发熔断判断 + fallback
3. 关键细节:什么情况会真正触发 fallback?
fallback 并非只要抛异常就执行,它只在以下任一条件满足时激活:
- 业务代码抛出了被
recordExceptions列出的异常(如TimeoutException),且该次调用导致熔断器状态变为 OPEN 或 HALF_OPEN 后仍失败 - 熔断器当前处于 OPEN 状态,此时即使没抛异常(比如直接拒绝请求),也会跳过原始调用,直接进入 fallback
- 注意:
ignoreExceptions中的异常不会增加失败计数,也不会触发 fallback —— 它们被视为“正常流程的一部分”
4. 补充:配合 Retry 实现更稳健的降级策略
若希望先重试几次再降级,可把 Retry 插入装饰链中(顺序很重要):
Retry retry = Retry.of("myService", RetryConfig.custom()
.maxAttempts(3)
.retryExceptions(TimeoutException.class) // 只对这类异常重试
.build());
Supplier<String> decorated = Decorators.ofSupplier(() -> callRemote())
.withCircuitBreaker(circuitBreaker)
.withRetry(retry)
.withFallback(t -> "fallback_result");
此时执行顺序是:调用 → 失败且匹配 retry 异常 → 重试最多 3 次 → 全部失败或触发熔断 → 进入 fallback。


















