前言
在某些场景,由于网络的不稳定性或者是IO的瓶颈,我们在某个操作的时候,如果有异常,我们希望是先重试几次,如果还是不行,才对这个事件进行补偿返回。这个时刻,我们可以使用Spring retry的一个小工具了。原理也很简单,其实就是使用AOP的原理。众所周知,Spring的AOP实现有2种机制,一个是JDK的动态带来,一个是CGLIB生成代码的方式实现。
使用
- 引入依赖
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <!-- 因为依赖AOP,所以必须引入AOP,如果有了,可以忽略 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
- 在Spring 的启动类或者配置类中,添加注解 @EnableRetr
public @interface EnableRetry { /** * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed * to standard Java interface-based proxies. The default is {@code false}. * * @return whether to proxy or not to proxy the class */ boolean proxyTargetClass() default false; }
里面的参数,proxyTargetClass :是否使用CGLIB模式的动态代理,默认是否,则是使用JDK的动态代理
- 在对应的方法上,添加重试注解,主要是有2个注解
@Retryable : 重试的方法
@Recover:重试都失败后的补偿机制
4.例子
public interface RetryService {
@Retryable(value = RuntimeException.class,
label = "测试案例",
maxAttempts = 8,
backoff = @Backoff(delay = 200,multiplier = 1))
void firstRetry();
@Recover
void recover(RuntimeException e);
}
注意事项
- 补偿方法,需要使用@Recover 修饰,而且补偿方法的返回类型必须跟被补偿方法的返回类型一致
- 如果同一个类中,有多个需要补偿的方法,以及多个补偿方法,对应关系如下:
①先通过补抓的异常的类型,拿精确度最高的一个
②补抓异常相同的时候,看返回值- 如果使用JDK的动态代理的话,这2个注解,既可以放在interface上,也可以放在实现类上,而且使用的对象,不一定有接口都可以实现。