> ## Documentation Index
> Fetch the complete documentation index at: https://blog.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Spring Framework 7.0 内置容错功能：告别 spring-retry

> Spring Framework 7.0 引入了内置的容错功能，通过 @Retryable 和 @ConcurrencyLimit 注解，无需再单独引入 spring-retry 模块即可实现重试和并发控制能力。

> Spring Framework 7.0 引入了内置的容错（Resilience）功能，通过 `@Retryable` 和 `@ConcurrencyLimit` 注解，开发者无需再单独引入 spring-retry 模块即可实现重试和并发控制能力。

## 概述

随着现代分布式应用程序复杂性的不断增加，系统的健壮性和可靠性成为了开发者面临的重要挑战。网络波动、外部服务暂时不可用、数据库连接超时等问题在生产环境中屡见不鲜。为了应对这些挑战，开发者通常需要实现重试机制（Retry Mechanism）、并发控制（Concurrency Control）、熔断降级（Circuit Breaker）等容错设计模式（Resilience Design Patterns）来提高系统的容错能力。

笔者在开发 AI 应用时，在研究国内某厂商的 AI SDK 源码时发现，其重试和超时处理竟然还在使用原始的 for-while 循环实现，代码冗长且容易出错。相比之下，Spring Framework 7.0 的内置容错功能提供了真正现代化的解决方案，通过声明式注解配置即可实现复杂的重试策略，无需手写繁琐的循环逻辑，代码简洁优雅且功能强大。

在 Spring Framework 7.0.0-M6 版本中，官方正式引入了 `org.springframework.core.retry` 包，将原本属于独立项目 "spring-retry" 的功能集成到了核心框架中。这一重要变化意味着从 Spring Framework 7.0 开始，开发者可以直接使用框架内置的容错功能来构建更加健壮的应用程序，无需额外引入依赖就能轻松应对各种故障场景。

主要新增的注解包括：

* `@Retryable`：方法重试功能（Method Retry）
* `@ConcurrencyLimit`：并发限制功能（Concurrency Throttling）

## @Retryable 重试功能

### 基本使用

`@Retryable` 注解可以应用在方法级别或类级别，为方法调用提供重试能力：

```java theme={null}
@Retryable
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}
```

**默认重试策略：**

* 对任何异常都会重试
* 最多重试 3 次（initial failure + 3 retries）
* 重试间隔为 1 秒（固定延迟策略）

### 自定义重试策略

#### 指定重试的异常类型

只对特定异常类型进行重试，提高重试的精准性：

```java theme={null}
@Retryable(MessageDeliveryException.class)
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}
```

#### 高级重试策略配置

配置更复杂的重试策略，包括指数退避算法（Exponential Backoff）：

```java theme={null}
@Retryable(
    maxAttempts = 5,      // 最大重试次数
    delay = 100,          // 初始延迟（毫秒）
    jitter = 10,          // 随机抖动（Jitter），避免重试风暴
    multiplier = 2,       // 指数退避倍数
    maxDelay = 1000       // 最大延迟上限
)
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}
```

该配置采用指数退避算法，重试间隔计算公式：`delay * multiplier^attempt + jitter`，有效避免了重试风暴（Retry Storm）问题。

### 响应式编程支持

对于返回响应式类型（Reactive Types）的方法，`@Retryable` 会自动装饰 Project Reactor 的重试管道：

```java theme={null}
@Retryable(maxAttempts = 5, delay = 100, jitter = 10, multiplier = 2, maxDelay = 1000)
public Mono<Void> sendNotification() {
    return Mono.from(...);  // 原始 Mono 流会被重试策略自动装饰
}
```

这种集成确保了响应式流（Reactive Streams）的重试逻辑与传统阻塞式调用保持一致的配置体验。

## @ConcurrencyLimit 并发控制

### 基本使用

`@ConcurrencyLimit` 注解用于实现并发限流（Concurrency Throttling），限制方法的并发访问数量：

```java theme={null}
@ConcurrencyLimit(10)  // 最多允许 10 个并发请求
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}
```

### 独占访问模式

设置限制为 1 可以实现对目标 Bean 实例的独占访问（Exclusive Access）：

```java theme={null}
@ConcurrencyLimit(1)  // 串行执行，确保线程安全
public void sendNotification() {
    this.jmsClient.destination("notifications").send(...);
}
```

## 总结

Spring Framework 7.0 的内置容错功能（Built-in Resilience Features）为开发者提供了开箱即用的重试和并发控制能力，这不仅简化了项目依赖管理，还提供了更优的性能表现和更深度的框架集成体验。 **现有项目**：可在升级到 Spring Boot 4.0 时逐步迁移，享受更好的性能和维护体验。
