天天看點

spring-retry注解自動觸發重試

用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異常");
    }
    
    @Recover
    public void recover(IllegalAccessException e){
        System.out.println("service retry after Recover => " + e.getMessage());
    }

}
           

其中要在測試類上面打注解@EnableRetry,測試方法上面打注冊@Retryable,’@Retryable’注解中,maxAttempts是最大嘗試次數,backoff是重試政策,value 是初始重試間隔毫秒數,預設是3000l,multiplier是重試乘數,例如第一次是3000l,第二次是3000lmultiplier,第三次是3000lmultiplier2如此類推,maxDelay是最大延遲毫秒數,如果3000lmultiplier*n>maxDelay,延時毫秒數會用maxDelay。

@Recover

當重試次數耗盡依然出現異常時,執行此異常對應的@Recover方法。

異常類型需要與Recover方法參數類型保持一緻,

recover方法傳回值需要與重試方法傳回值保證一緻

延遲時間分别是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;
    }
}
           

繼續閱讀