Spring Retry提供了一种声明式的方法来处理那些可能会失败的操作,允许你在遇到异常时自动重试这些操作。以下是如何在Spring应用程序中使用Spring Retry的基本步骤:
添加依赖
首先,你需要在项目的pom.xml
文件中添加Spring Retry的依赖。如果你使用的是Spring Boot,通常已经包含了 Spring Retry 的依赖。
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>你的Spring Retry版本</version>
</dependency>
在启动类上添加@EnableRetry
// 失败重试
@EnableRetry
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
使用@Retryable注解、@Recover
- 使用
@Retryable
注解来标记需要重试的方法,可以指定哪些异常会触发重试,以及重试的次数和延迟。 - 使用
@Recover
注解来定义一个恢复方法,当重试次数耗尽后,这个方法会被调用。
/**
* 学习Spring Retry的Service
*
* @author 付聪
* @time 2024-10-25 11:35:34
*/
@Service
public class LearnSpringRetryService {
private static final Logger logger = LoggerFactory.getLogger(LearnSpringRetryService.class);
// 抛出Exception异常时最多重试3次,每次重试之间有1秒的延迟,每次重试的延迟时间是前一次的2倍。
@Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
public void test() {
// 可能会抛出异常的代码
logger.error("执行【LearnSpringRetryService.test】方法,即将抛异常!");
throw new RuntimeException("执行【LearnSpringRetryService.test】方法,出现异常!");
}
@Recover
public void recover(Exception e) {
// 重试失败后的恢复逻辑
logger.info("执行【LearnSpringRetryService.recover】方法,成功!");
}
}
测试验证
/**
* LearnSpringRetryService测试
*
* @author 付聪
* @time 2024-10-25 11:45:18
*/
public class LearnSpringRetryServiceTest extends MainApplicationTests {
private static final Logger logger = LoggerFactory.getLogger(LearnSpringRetryServiceTest.class);
@Resource
private LearnSpringRetryService learnSpringRetryService;
@Test
public void test01() {
learnSpringRetryService.test();
PrintUtil.println("执行【learnSpringRetryService.test】方法,完成!");
}
}
验证结果
———————————————————————— 开始测试单个方法 ————————————————————————
2024-10-25 11:49:31,527 ERROR [main] p.f.c.l.r.LearnSpringRetryService.test(25): 执行【LearnSpringRetryService.test】方法,即将抛异常!
2024-10-25 11:49:32,530 ERROR [main] p.f.c.l.r.LearnSpringRetryService.test(25): 执行【LearnSpringRetryService.test】方法,即将抛异常!
2024-10-25 11:49:34,539 ERROR [main] p.f.c.l.r.LearnSpringRetryService.test(25): 执行【LearnSpringRetryService.test】方法,即将抛异常!
2024-10-25 11:49:34,539 INFO [main] p.f.c.l.r.LearnSpringRetryService.recover(32): 执行【LearnSpringRetryService.recover】方法,成功!
执行【learnSpringRetryService.test】方法,完成!
———————————————————————— 结束测试单个方法 ————————————————————————