spring-retry注解自动触发重试

用spring-retry注解自动触发重试方法

依赖

        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
<!--            <version>1.2.2.RELEASE</version>-->
        </dependency>
@EnableRetry
public class  needRetryService {

      @Retryable(include = SomeException.class, maxAttempts = 3)
       public void needRetryFunction {
           if (condition){
          throws new SomeException("some exception occur!");
       }
       
    @Retryable(maxAttempts = 5,backoff = @Backoff(multiplier = 2,value = 2000L,maxDelay = 10000L))
    public void retry(){
        System.out.println(new Date());
        throw new RuntimeException("retry异常");
    }
}

其中要在测试类上面打注解@EnableRetry,测试方法上面打注册@Retryable,’@Retryable’注解中,maxAttempts是最大尝试次数,backoff是重试策略,value 是初始重试间隔毫秒数,默认是3000l,multiplier是重试乘数,例如第一次是3000l,第二次是3000lmultiplier,第三次是3000lmultiplier2如此类推,maxDelay是最大延迟毫秒数,如果3000lmultiplier*n>maxDelay,延时毫秒数会用maxDelay。

延迟时间分别是2、4、8、10s。

实现原理:

@Component
@Aspect
public class Aop {
    protected org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());

    @Pointcut("@annotation(com.eujian.springretry.myanno.MyRetryable)")
    public void pointCutR() {
    }
    /**
     * 埋点拦截器具体实现
     */
    @Around("pointCutR()")
    public Object methodRHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        MyRetryable myRetryable = targetMethod.getAnnotation(MyRetryable.class);
        MyBackoff backoff = myRetryable.backoff();
        int maxAttempts = myRetryable.maxAttempts();
        long sleepSecond = backoff.value();
        double multiplier = backoff.multiplier();
        if(multiplier<=0){
            multiplier = 1;
        }
        Exception ex = null;
        int retryCount = 1;
        do{
            try {

                Object proceed = joinPoint.proceed();
                return proceed;
            }catch (Exception e){
                logger.info("睡眠{}毫秒",sleepSecond);
                Thread.sleep(sleepSecond);
                retryCount++;
                sleepSecond = (long)(multiplier)*sleepSecond;
                if(sleepSecond>backoff.maxDelay()){
                    sleepSecond = backoff.maxDelay();
                    logger.info("睡眠时间太长,改成{}毫秒",sleepSecond);
                }
                ex = e;

            }
        }while (retryCount<maxAttempts);

        throw ex;
    }
}
上一篇:交替方向乘子法(Alternating Direction Multiplier Method,ADMM)


下一篇:开启IDEA打开新项目时窗口提示