Spring 重试接口和回滚接口
添加Spring Retry依赖
要在Spring Boot项目中使用@Retryable注解实现重试功能,需要在pom.xml中添加以下两个关键依赖:
<!-- Spring Retry核心依赖 -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<!-- AspectJ支持,用于AOP实现 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
使用说明
添加依赖后,还需要在Spring Boot应用的主配置类上添加@EnableRetry注解来启用重试功能:
@SpringBootApplication
@EnableRetry // 添加此注解启用重试功能
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
然后就可以在需要重试的方法上使用@Retryable注解了,例如:
@Retryable(
retryFor = {Exception.class}, // 指定哪些异常需要重试
maxAttempts = 3, // 最大重试次数
backoff = @Backoff(
delay = 1000, // 重试间隔时间(毫秒)
multiplier = 2 // 间隔时间的递增倍数
)
)
public void someMethod() {
// 可能需要重试的操作
}
这些配置将使您能够在项目中正确使用Spring Retry的@Retryable注解功能。
public class SupplyChainSagaService {
@Autowired
private SupplyChainClient supplyChainClient;
@Autowired
private SagaFailedTaskService failedTaskService;
// 异步+重试执行SAGA
@Async
@Retryable(
value = Exception.class,
maxAttempts = 3, // 最大重试3次(含首次)
backoff = @Backoff(delay = 1000)
)
public void asyncCommitWithRetry(Order order) {
supplyChainClient.commit(null, order);
}
// 重试耗尽后执行:保存失败任务到数据库
@Recover
public void recover(Exception e, Order order) {
System.err.println("SAGA重试耗尽,订单ID:" + order.getId() + ",异常:" + e.getMessage());
// 保存失败任务到数据库,等待人工触发
failedTaskService.saveFailedTask(order, e);
}
}

浙公网安备 33010602011771号