欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring-Retry的使用详解

程序员文章站 2022-06-23 13:00:24
目录1 spring-retry的简介2 spring中的应用1 导入maven坐标2 添加被调用类3 添加测试类3 springboot中的应用1 导入maven坐标2 添加一个管理类3 启动类上添...

1 spring-retry的简介

在日常的一些场景中, 很多需要进行重试的操作.而spring-retry是spring提供的一个基于spring的重试框架,非常简单好用.

2 spring中的应用

1 导入maven坐标

 <dependency>
    <groupid>org.springframework.retry</groupid>
    <artifactid>spring-retry</artifactid>
    <version>1.2.2.release</version>
 </dependency>

2 添加被调用类

@slf4j
public class retrydemo {

    public static boolean retrymethod(integer param) {
        int i = new random().nextint(param);
        log.info("随机生成的数:{}", i);

        if (1 == i) {
            log.info("为1,返回true.");
            return true;
        } else if (i < 1) {
            log.info("小于1,抛出参数异常.");
            throw new illegalargumentexception("参数异常");
        } else if (i > 1 && i < 10) {
            log.info("大于1,小于10,抛出参数异常.");
            return false;
        } else {
            //为其他
            log.info("大于10,抛出自定义异常.");
            throw new remoteaccessexception("大于10,抛出自定义异常");
        }
    }
}

3 添加测试类

@slf4j
public class springretrytest {

    /**
     * 重试间隔时间ms,默认1000ms
     */
    private long fixedperiodtime = 1000l;
    /**
     * 最大重试次数,默认为3
     */
    private int maxretrytimes = 3;
    /**
     * 表示哪些异常需要重试
     * key一定要为throwable异常的子类    class<? extends throwable>
     * value为true表示需要重试
     */
    private map<class<? extends throwable>, boolean> exceptionmap = new hashmap<>();


    @test
    public void test() {

        // 1 添加异常的处理结果 true为需要重试 false为不需要重试
        exceptionmap.put(remoteaccessexception.class, true);

        // 2 构建重试模板实例
        retrytemplate retrytemplate = new retrytemplate();

        // 3 设置重试回退操作策略  设置重试间隔时间
        fixedbackoffpolicy backoffpolicy = new fixedbackoffpolicy();
        backoffpolicy.setbackoffperiod(fixedperiodtime);

        // 4 设置重试策略  设置重试次数 设置异常处理结果
        simpleretrypolicy retrypolicy = new simpleretrypolicy(maxretrytimes, exceptionmap);

        //5 重试模板添加重试策略 添加回退操作策略
        retrytemplate.setretrypolicy(retrypolicy);
        retrytemplate.setbackoffpolicy(backoffpolicy);
    
        // 6 调用方法
        boolean resp = retrytemplate.execute(
                // retrycallback 重试回调方法
                retrycontext -> {
                    boolean result = retrydemo.retrymethod(110);
                    log.info("方法返回结果= {}", result);
                    return result;
                },
                // recoverycallback 异常回调方法
                retrycontext -> {
                    //
                    log.info("超过最大重试次数或者抛出了未定义的异常!!!");
                    return false;
                }
        );

        log.info("接口返回结果 = {}",resp);

    }

}
/*
 // 查看结果
 [main] info com.cf.demo.springretry.springretrytest - 超过最大重试次数或者抛出了未定义的异常!!!
 [main] info com.cf.demo.springretry.springretrytest - 接口返回结果 = false
*/

从代码的书写注解可以看到,retrytemplate对象是spring-retry框架的重试执行者, 由它添加重试策略,回退操作策略等(注释第五步).retrytemplate执行重试方法(注释第六步),通过execute方法, 传入的参数是重试回调逻辑对象retrycallback 和执行操作结束的恢复对象recoverycallback. 且可以切换添加的异常种类, 得知,只有添加过相应的异常,才会触发重试操作,否则直接调用recoverycallback对象方法.

retrytemplate的部分源码:

 /**
  * keep executing the callback until it either succeeds or the policy dictates that we
  * stop, in which case the recovery callback will be executed.
  *
  * @see retryoperations#execute(retrycallback, recoverycallback)
  * @param retrycallback the {@link retrycallback}
  * @param recoverycallback the {@link recoverycallback}
  * @throws terminatedretryexception if the retry has been manually terminated by a
  * listener.
  */
 @override
 public final <t, e extends throwable> t execute(retrycallback<t, e> retrycallback,
   recoverycallback<t> recoverycallback) throws e {
  return doexecute(retrycallback, recoverycallback, null);
 }

retrytemplate添加重试策略源码:

 /**
  * setter for {@link retrypolicy}.
  *
  * @param retrypolicy the {@link retrypolicy}
  */
 public void setretrypolicy(retrypolicy retrypolicy) {
  this.retrypolicy = retrypolicy;
 }

retrypolicy接口的实现类:

alwaysretrypolicy:允许无限重试,直到成功,可能会导致死循环

circuitbreakerretrypolicy:有熔断功能的重试策略,需设置3个参数opentimeout、resettimeout和delegate

compositeretrypolicy:组合重试策略,有两种组合方式,乐观组合重试策略是指只要有一个策略允许即可以重试,
悲观组合重试策略是指只要有一个策略不允许即可以重试,但不管哪种组合方式,组合中的每一个策略都会执行

exceptionclassifierretrypolicy:设置不同异常的重试策略,类似组合重试策略,区别在于这里只区分不同异常的重试

neverretrypolicy:只允许调用retrycallback一次,不允许重试

simpleretrypolicy:固定次数重试策略,默认重试最大次数为3次,retrytemplate默认使用的策略

timeoutretrypolicy:超时时间重试策略,默认超时时间为1秒,在指定的超时时间内允许重试

retrytemplate添加回退策略源码:

 /**
  * setter for {@link backoffpolicy}.
  *
  * @param backoffpolicy the {@link backoffpolicy}
  */
 public void setbackoffpolicy(backoffpolicy backoffpolicy) {
  this.backoffpolicy = backoffpolicy;
 }

backoffpolicy的实现类:

exponentialbackoffpolicy:指数退避策略,需设置参数sleeper、initialinterval、maxinterval和multiplier,initialinterval指定初始休眠时间,默认100毫秒,maxinterval指定最大休眠时间,默认30秒,multiplier指定乘数,即下一次休眠时间为当前休眠时间*multiplier

exponentialrandombackoffpolicy:随机指数退避策略,引入随机乘数可以实现随机乘数回退

fixedbackoffpolicy:固定时间的退避策略,需设置参数sleeper和backoffperiod,sleeper指定等待策略,默认是thread.sleep,即线程休眠,backoffperiod指定休眠时间,默认1秒

nobackoffpolicy:无退避算法策略,每次重试时立即重试

uniformrandombackoffpolicy:随机时间退避策略,需设置sleeper、minbackoffperiod和maxbackoffperiod,该策略在[minbackoffperiod,maxbackoffperiod之间取一个随机休眠时间,minbackoffperiod默认500毫秒,maxbackoffperiod默认1500毫秒

3 springboot中的应用

1 导入maven坐标

 <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.1</version>
 </dependency>

2 添加一个管理类

@service
@slf4j
public class springretrydemo {


    /**
     * 重试所调用方法
     * @return
     */
    // delay=2000l表示延迟2秒 multiplier=2表示两倍 即第一次重试2秒后,第二次重试4秒后,第三次重试8秒后
    @retryable(value = {remoteaccessexception.class}, maxattempts = 3, backoff = @backoff(delay = 2000l, multiplier = 2))
    public boolean call(integer param) {
        return retrydemo.retrymethod(param);
    }

    /**
     * 超过最大重试次数或抛出没有指定重试的异常
     * @param e
     * @param param
     * @return
     */
    @recover
    public boolean recover(exception e, integer param) {
        log.info("请求参数为: ", param);
        log.info("超过最大重试次数或抛出没有指定重试的异常, e = {} ", e.getmessage());
        return false;
    }
}

3 启动类上添加注解@enableretry

@springbootapplication
@enableretry
public class demoapplication {

    public static void main(string[] args) {
        springapplication.run(demoapplication.class, args);
    }
}    

4 添加测试类

@runwith(springrunner.class)
@springboottest(classes = demoapplication.class)
@slf4j
public class demoapplicationtests {

    @autowired
    private springretrydemo springretrydemo;

    @test
    public void testretry() {
        boolean result = springretrydemo.call(110);
        log.info("方法返回结果为: {}", result);
    }
}
/* 运行结果:

    随机生成的数:77
    大于10,抛出自定义异常.
    随机生成的数:23
    大于10,抛出自定义异常.
    随机生成的数:82
    大于10,抛出自定义异常.
    请求参数为: 
    超过最大重试次数或抛出没有指定重试的异常, e = 大于10,抛出自定义异常 
    方法返回结果为: false
*/

注解说明:
@enableretry注解,启用重试功能(默认是否基于子类代理,默认是否, 即是基于java接口代理)

@target(elementtype.type)
@retention(retentionpolicy.runtime)
@enableaspectjautoproxy(proxytargetclass = false)
@import(retryconfiguration.class)
@documented
public @interface enableretry {

 /**
  * indicate whether subclass-based (cglib) proxies are to be created as opposed
  * to standard java interface-based proxies. the default is {@code false}.
  *
  * @return whether to proxy or not to proxy the class
  */
 boolean proxytargetclass() default false;

}

@retryable注解, 标记的方法发生异常时会重试

  • value  指定发生的异常进行重试
  • include  与value一样,默认为空,当exclude同时为空时,所有异常都重试
  • exclude  指定异常不重试,默认为空,当include同时为空,所有异常都重试
  • maxattemps  重试次数,默认3
  • backoff  重试补充机制  默认是@backoff()注解
@target({ elementtype.method, elementtype.type })
@retention(retentionpolicy.runtime)
@documented
public @interface retryable {

 /**
  * retry interceptor bean name to be applied for retryable method. is mutually
  * exclusive with other attributes.
  * @return the retry interceptor bean name
  */
 string interceptor() default "";

 /**
  * exception types that are retryable. synonym for includes(). defaults to empty (and
  * if excludes is also empty all exceptions are retried).
  * @return exception types to retry
  */
 class<? extends throwable>[] value() default {};

 /**
  * exception types that are retryable. defaults to empty (and if excludes is also
  * empty all exceptions are retried).
  * @return exception types to retry
  */
 class<? extends throwable>[] include() default {};

 /**
  * exception types that are not retryable. defaults to empty (and if includes is also
  * empty all exceptions are retried).
  * @return exception types to retry
  */
 class<? extends throwable>[] exclude() default {};

 /**
  * a unique label for statistics reporting. if not provided the caller may choose to
  * ignore it, or provide a default.
  *
  * @return the label for the statistics
  */
 string label() default "";

 /**
  * flag to say that the retry is stateful: i.e. exceptions are re-thrown, but the
  * retry policy is applied with the same policy to subsequent invocations with the
  * same arguments. if false then retryable exceptions are not re-thrown.
  * @return true if retry is stateful, default false
  */
 boolean stateful() default false;

 /**
  * @return the maximum number of attempts (including the first failure), defaults to 3
  */
 int maxattempts() default 3;

 /**
  * @return an expression evaluated to the maximum number of attempts (including the first failure), defaults to 3
  * overrides {@link #maxattempts()}.
  * @since 1.2
  */
 string maxattemptsexpression() default "";

 /**
  * specify the backoff properties for retrying this operation. the default is a
  * simple {@link backoff} specification with no properties - see it's documentation
  * for defaults.
  * @return a backoff specification
  */
 backoff backoff() default @backoff();

 /**
  * specify an expression to be evaluated after the {@code simpleretrypolicy.canretry()}
  * returns true - can be used to conditionally suppress the retry. only invoked after
  * an exception is thrown. the root object for the evaluation is the last {@code throwable}.
  * other beans in the context can be referenced.
  * for example:
  * <pre class=code>
  *  {@code "message.contains('you can retry this')"}.
  * </pre>
  * and
  * <pre class=code>
  *  {@code "@somebean.shouldretry(#root)"}.
  * </pre>
  * @return the expression.
  * @since 1.2
  */
 string exceptionexpression() default "";
}

@backoff注解

  • delay  延迟多久后重试
  • multiplier  延迟的倍数
@target(elementtype.type)
@retention(retentionpolicy.runtime)
@import(retryconfiguration.class)
@documented
public @interface backoff {

 /**
  * synonym for {@link #delay()}.
  *
  * @return the delay in milliseconds (default 1000)
  */
 long value() default 1000;

 /**
  * a canonical backoff period. used as an initial value in the exponential case, and
  * as a minimum value in the uniform case.
  * @return the initial or canonical backoff period in milliseconds (default 1000)
  */
 long delay() default 0;

 /**
  * the maximimum wait (in milliseconds) between retries. if less than the
  * {@link #delay()} then the default of
  * {@value org.springframework.retry.backoff.exponentialbackoffpolicy#default_max_interval}
  * is applied.
  *
  * @return the maximum delay between retries (default 0 = ignored)
  */
 long maxdelay() default 0;

 /**
  * if positive, then used as a multiplier for generating the next delay for backoff.
  *
  * @return a multiplier to use to calculate the next backoff delay (default 0 =
  * ignored)
  */
 double multiplier() default 0;

 /**
  * an expression evaluating to the canonical backoff period. used as an initial value
  * in the exponential case, and as a minimum value in the uniform case.
  * overrides {@link #delay()}.
  * @return the initial or canonical backoff period in milliseconds.
  * @since 1.2
  */
 string delayexpression() default "";

 /**
<<<<<<< head
  * an expression evaluating to the maximum wait (in milliseconds) between retries.
  * if less than the {@link #delay()} then ignored.
=======
  * an expression evaluating to the maximimum wait (in milliseconds) between retries.
  * if less than the {@link #delay()} then the default of
  * {@value org.springframework.retry.backoff.exponentialbackoffpolicy#default_max_interval}
  * is applied.
>>>>>>> fix @backoff javadocs - maxdelay
  * overrides {@link #maxdelay()}
  *
  * @return the maximum delay between retries (default 0 = ignored)
  * @since 1.2
  */
 string maxdelayexpression() default "";

 /**
  * evaluates to a vaule used as a multiplier for generating the next delay for backoff.
  * overrides {@link #multiplier()}.
  *
  * @return a multiplier expression to use to calculate the next backoff delay (default 0 =
  * ignored)
  * @since 1.2
  */
 string multiplierexpression() default "";

 /**
  * in the exponential case ({@link #multiplier()} &gt; 0) set this to true to have the
  * backoff delays randomized, so that the maximum delay is multiplier times the
  * previous delay and the distribution is uniform between the two values.
  *
  * @return the flag to signal randomization is required (default false)
  */
 boolean random() default false;

}

@recover注解

当重试达到规定的次数后,被注解标记的方法将被调用, 可以在此方法中进行日志的记录等操作.(该方法的入参类型,返回值类型需要和重试方法保持一致)

@target({ elementtype.method, elementtype.type })
@retention(retentionpolicy.runtime)
@import(retryconfiguration.class)
@documented
public @interface recover {
}

参考资料:
https://blog.csdn.net/zzzgd_666/article/details/84377962

到此这篇关于spring-retry的使用详解的文章就介绍到这了,更多相关spring-retry 使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Spring-Retry 使用