zoukankan      html  css  js  c++  java
  • 用spring-retry注解自动触发重试方法

    原文地址:https://www.jianshu.com/p/ee02d6125113

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

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

    org.springframework.boot spring-boot-starter-web org.springframework.retry spring-retry org.aspectj aspectjweaver 1.9.2 org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine 三、编写测试类

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

    }
    运行测试类效果

  • 相关阅读:
    Java设计模式--命令模式
    linux 挂载windows盘
    C# 对含有向量偏移的明文进行AES加解密
    Vue修仙之旅之Vue初尝
    Cookie的Secure属性
    Webserver信息泄露的解决方案--使用StripHeaders模块删除不必要的header
    window自定义事件
    vue typescript .eslintrc.js
    css word-break: break-word;无效
    vscode vue 片段
  • 原文地址:https://www.cnblogs.com/yeyongjian/p/13206810.html
Copyright © 2011-2022 走看看