一Spring-retry简介
有些场景需要我们对一些异常情况下面的任务进行重试,比如:调用远程的RPC服务,可能由于网络抖动出现第一次调用失败,尝试几次就可以恢复正常。
spring-retry是spring提供的一个基于spring的重试框架,非常好用。
官网地址: https://github.com/spring-projects/spring-retry
二、Maven依赖
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
三、重试使用
- 启动类添加注解@EnableRetry
@SpringBootApplication
@EnableTransactionManagement // 启注解事务管理
@EnableScheduling
@EnableRetry // 启用了重试功能
public class TestWebApplication {
public static void main(String[] args) {
SpringApplication.run(TestWebApplication.class, args);
}
}
- 业务方法重试
@Service
@Slf4j
public class RetryServiceImpl implements RetryService {
private AtomicInteger count = new AtomicInteger(1);
@Override
@Retryable(value = { RemoteAccessException.class }, maxAttemptsExpression = "${retry.maxAttempts:10}",
backoff = @Backoff(delayExpression = "${retry.backoff:1000}"))
public void retry() {
log.info("start to retry : " + count.getAndIncrement());
throw new RemoteAccessException("here " + count.get());
}
@Recover
public void recover(RemoteAccessException t) {
log.info("SampleRetryService.recover:{}", t.getClass().getName());
}
}
【注意】@Recover 的用法。它要求它注释的方法的返回值必须和@Retryable的注释的方法返回值保持一致,否则@Recover 注释的方法不会被调用。它还有关于自己参数的使用要求。
- 自定义retry
public static void main(String[] args) throws InterruptedException {
RetryTemplate template = new RetryTemplate();
TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
policy.setTimeout(2000L);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
// 重试策略
template.setRetryPolicy(retryPolicy);
String result = template.execute(context -> {
System.out.println("TestAll.main()1");
TimeUnit.SECONDS.sleep(1L);
throw new IllegalArgumentException();
}, context -> {
System.out.println("TestAll.main()2");
return "world";
});
System.out.println("result:" + result);
}
【注意】
interface RetryPolicy 它有很多的实现类可以使用。
四、常用注解
- @Retryable注解
被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有 - @Backoff注解
delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒 - @Recover
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调。