SpringBoot如何优雅的实现重试功能
文章目录
- 使用背景
- spring-retry介绍
- 快速使用
- 加入依赖
- 开启Retry
- 使用
- 参数
使用背景
在有些特定场景,如和第三方对接。
我们调用接口时需要支持重试功能,第一次调用没成功,我们需要等待x秒后再次调用。
通常会设置重试次数,避免业务。
一般我们会这样写
public ApiResponse<Boolean> test() {//模拟调用System.out.println("开始调用,第" + num + "次");//业务逻辑boolean result = false;if (result) {System.out.println("执行完成!");} else if (num >= totalNum) {System.out.println("重试结束");num = 1;} else {System.out.println("重试");++num;test();}return ApiResponse.ok(true);
}
这样写本身,没什么问题。
但是如果多个接口都需要重试的话,代码就不优雅了。
spring-retry介绍
spring系列的spring-retry是另一个实用程序模块,
可以帮助我们以标准方式处理任何特定操作的重试。
在spring-retry中,所有配置都是基于简单注释的。
快速使用
加入依赖
<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
开启Retry
启动上增加注解@EnableRetry
@EnableRetry
使用
@GetMapping("test")
@Retryable(value = Exception.class,maxAttempts = 5,backoff = @Backoff(delay = 2000,multiplier = 1.5))
public ApiResponse<Boolean> test() {System.out.println("开始调用,第" + num + "次");boolean result = false;if (!result){num++;throw new BizException("调用失败,需要重试");}System.out.println("执行完成");return ApiResponse.ok(true);
}
参数
value:抛出指定异常才会重试
include:和value一样,默认为空,当exclude也为空时,默认所有异常
exclude:指定不处理的异常
maxAttempts:最大重试次数,默认5次
backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。