Spring 重試接口和回滾接口
添加Spring Retry依賴
要在Spring Boot項(xiàng)目中使用@Retryable注解實(shí)現(xiàn)重試功能,需要在pom.xml中添加以下兩個(gè)關(guān)鍵依賴:
<!-- Spring Retry核心依賴 -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<!-- AspectJ支持,用于AOP實(shí)現(xiàn) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
使用說明
添加依賴后,還需要在Spring Boot應(yīng)用的主配置類上添加@EnableRetry注解來啟用重試功能:
@SpringBootApplication
@EnableRetry // 添加此注解啟用重試功能
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
然后就可以在需要重試的方法上使用@Retryable注解了,例如:
@Retryable(
retryFor = {Exception.class}, // 指定哪些異常需要重試
maxAttempts = 3, // 最大重試次數(shù)
backoff = @Backoff(
delay = 1000, // 重試間隔時(shí)間(毫秒)
multiplier = 2 // 間隔時(shí)間的遞增倍數(shù)
)
)
public void someMethod() {
// 可能需要重試的操作
}
這些配置將使您能夠在項(xiàng)目中正確使用Spring Retry的@Retryable注解功能。
public class SupplyChainSagaService {
@Autowired
private SupplyChainClient supplyChainClient;
@Autowired
private SagaFailedTaskService failedTaskService;
// 異步+重試執(zhí)行SAGA
@Async
@Retryable(
value = Exception.class,
maxAttempts = 3, // 最大重試3次(含首次)
backoff = @Backoff(delay = 1000)
)
public void asyncCommitWithRetry(Order order) {
supplyChainClient.commit(null, order);
}
// 重試耗盡后執(zhí)行:保存失敗任務(wù)到數(shù)據(jù)庫
@Recover
public void recover(Exception e, Order order) {
System.err.println("SAGA重試耗盡,訂單ID:" + order.getId() + ",異常:" + e.getMessage());
// 保存失敗任務(wù)到數(shù)據(jù)庫,等待人工觸發(fā)
failedTaskService.saveFailedTask(order, e);
}
}

浙公網(wǎng)安備 33010602011771號(hào)