Spring Retry 是 Spring 生态中轻量、声明式、可配置的重试框架,适合服务间调用失败时自动重试;需添加 spring-retry 和 spring-aop 依赖,启用 @EnableRetry,用 @Retryable 注解方法并可配异常类型、最大尝试次数与退避策略,支持 @Recover 降级及编程式 RetryTemplate 动态控制。

Spring Retry 是 Spring 生态中轻量、声明式、可配置的重试框架,适合在服务间调用(如 HTTP、RPC)失败时自动重试。它不依赖外部中间件,通过注解或编程方式即可集成到 Spring Boot 项目中。
1. 添加依赖
在 Spring Boot 2.4+ 中,spring-retry 不再默认包含,需手动引入:
Gradle:
implementation 'org.springframework.retry:spring-retry'implementation 'org.springframework.boot:spring-boot-starter-aop'
注意:spring-aop 必须存在,因为 @Retryable 依赖 AOP 代理生效。
立即学习“Java免费学习笔记(深入)”;
2. 启用重试支持
在主启动类或任意配置类上添加 @EnableRetry:
@EnableRetry
public class MyApp { ... }
3. 在方法上使用 @Retryable 注解
将该注解加在需要重试的业务方法上(必须是 Spring 管理的 Bean 中的 public 方法):
@Servicepublic class UserService {
@Retryable(
value = {RestClientException.class, SocketTimeoutException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, multiplier = 2)
)
public User getUserById(Long id) {
return restTemplate.getForObject("https://api.example.com/users/" + id, User.class);
}
@Recover
public User recover(RestClientException e, Long id) {
log.warn("所有重试失败,返回默认用户,id={}", id);
return new User(0L, "default");
}
}
-
value:指定哪些异常触发重试(默认对所有异常重试) -
maxAttempts:最大尝试次数(含首次调用,即 3 表示最多执行 3 次) -
backoff.delay:首次重试延迟毫秒数(如 1000 = 1 秒) -
backoff.multiplier:延迟倍增因子(如 2 表示第2次等 2s,第3次等 4s) -
@Recover:定义降级方法,参数需匹配异常类型和原方法入参,返回值与原方法一致
4. 高级用法:动态重试策略
若需运行时决定是否重试或调整参数,可用编程式重试:
RetryTemplate template = RetryTemplate.builder().maxAttempts(5)
.exponentialBackoff(100, 2, 10000) // 初始延迟100ms,倍增2,上限10s
.retryOn(RestClientException.class)
.traverseCauses(true)
.build();
User user = template.execute(ctx -> {
return restTemplate.getForObject(url, User.class);
});
-
traverseCauses=true:检查异常链中的根本原因(如包装过的 IOException) -
exponentialBackoff支持设置最大重试间隔,避免指数爆炸 - 适合非 Spring Bean 方法、Lambda 调用或需按条件构造模板的场景


















