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

需求背景:
有些时候我们再调用一些第三方服务的时候,从第三方那边拉数据。
但是第三方服务不是100%稳定的,有些时候会抽风一下,导致我们的调用失败,整个调用链就失败。整个时候需要触发重试,而且不是一直死循环重试,因为第三方服务器不稳定的情况下一直循环也是大概率失败,而是应该每隔一段时间重试一次,例如第二次重试是30s后,第三次重试是60s后,第四次重试是120s后如此类推。

这个时候我就想到到spring-retry,下面是spring-retry的使用教学
一、新建springboot工程
二、引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
<!--            <version>1.2.2.RELEASE</version>-->
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

三、编写测试类

@Component
@EnableRetry
public class RetryService  {


    @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。

四、运行单元测试类,效果如下


image.png

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

实现原理

我们可以通过写一个自己的注解去实现同样的逻辑
@MyBackoff注解类

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBackoff {
    long value() default 1000L;

    long maxDelay() default 0L;

    double multiplier() default 0.0D;
}

@MyRetryable注解类

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyBackoff {
    long value() default 1000L;

    long maxDelay() default 0L;

    double multiplier() default 0.0D;
}

aop切面类

@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;
    }
}

运行测试类效果


image.png

github地址:https://github.com/hd-eujian/springretry.git
码云地址:https://gitee.com/guoeryyj/springretry.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。