1、背景
- 调用第三方接口,按照最大次数轮询去获取结果,或因为网络波动导致超时等原因导致返回失败情况。
- Retry重试框架,支持AOP切入的方式使用,支持注解;重试次数、重试延迟、重试触发条件、重试的回调方法等功能来实现重试机制
2、相关配置
pom文件
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
启动类增加 @EnableRetry 注解
3、测试代码
@Api(value = "重试测试") @RestController(value = "/retry") public class RetryController { @Autowired private RetryService retryService; @ApiOperation(value = "测试重试") @GetMapping("/do") public void retry() { try { int retry = retryService.retry(0); } catch (Exception e) { e.printStackTrace(); } } } public class RetryService { private final static int TOTAL_NUM = 10; /** * @Retryable: 标记当前方法使用重试机制 value:触发重试机制的条件,当遇到Exception时,会重试 * <p> * maxAttempts :设置最大重试次数,默认为5次 * <p> * delay:重试延迟时间,单位毫秒,即距离上一次重试方法的间隔 * <p> * multiplier:delay重试延迟时间的间隔倍数,即第一次为5秒,第二次为5乘以2为10秒,依此类推 */ @Retryable(value = Exception.class, maxAttempts = 5, backoff = @Backoff(delay = 5000L, multiplier = 2)) public int retry(int num) throws Exception { log.info("getAmount======开始执行" + LocalTime.now()); if (num <= 1) { throw new ServiceException("参数小于1"); } log.info("getAmount======执行结束"); return TOTAL_NUM - num; } }
4、验证结果
根据执行时间可以看出重试执行的时间间隔依次递增。
5、注意事项
- @Retryable只能写在接口的实现类对应的方法上
- 使用的 方法必须是抛出异常形式