Spring retry重试机制

demo

pom.xml

        
            org.springframework.retry
            spring-retry
            1.2.4.RELEASE
        

测试

public static void main(String[] args) {
        RetryTemplate retryTemplate=new RetryTemplate();
        retryTemplate.setRetryPolicy(new SimpleRetryPolicy(10));
        AtomicInteger counter = new AtomicInteger();
        retryTemplate.execute(f->{
            if(counter.incrementAndGet()<20){
                System.out.println(counter.intValue());
                throw new IllegalStateException();
            }
            return counter.incrementAndGet();
        });
    }

RetryTemplate默认重试3次,我们可以自定义SimpleRetryPolicy的重试次数

抛出异常是为了重试

 

总结,当我们重试超过指定次数时候,抛出异常,它会报错的。

Exception in thread "main" java.lang.IllegalStateException
    at com.example.demo.Test.lambda$main$0(Test.java:22)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
    at com.example.demo.Test.main(Test.java:19)

所以在重试的时候还要在外层加上try,catch进行相应的处理

或者不加让他直接报错出来我们自己处理

 

重试注解

 

aop注解

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)  // 保留到运行时,可通过注解获取
@Documented
public @interface MyRetry {

    /**
     * 重试次数
     * @return
     */
    int times() default 1;

}

 

aop切面编程

/**
 * @author 大鸡腿
 * 重试抛出RetryBusinessException,其他异常重试注解不起作用
 */
@Slf4j
@Aspect
@Component
public class MyRetryAspect {

    @Pointcut("@annotation(com.yatsenglobal.cloud.retry.MyRetry)")
    public void annotationPoinCut() {

    }

    @Around(value = "annotationPoinCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //获取方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取切入方法的对象
        Method method = signature.getMethod();
        //获取方法上的Aop注解
        MyRetry myMethod = method.getAnnotation(MyRetry.class);
        //重试
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setRetryPolicy(new SimpleRetryPolicy(myMethod.times()));
        return retryTemplate.execute(f -> {
            Object result;
            try {
                result = point.proceed();
            } catch (RetryBusinessException e) {
                throw new RetryBusinessException(ActivityErrorCodeEnum.AC52000200);
            }
            return result;
        });
    }

}

 

RetryBusinessException

这个自己定义

@EqualsAndHashCode(callSuper = true)
@Data
public class RetryBusinessException extends BusinessException {

    private static final long serialVersionUID = -8081770607525925770L;

    public RetryBusinessException(ActivityErrorCodeEnum codeEnum) {
        super(codeEnum.code(), codeEnum.msg());
    }

}

 

你可能感兴趣的:(spring)