Spring-Retry的使用详解

目录
  • 1 Spring-Retry的简介
  • 2 Spring中的应用
    • 1 导入maven坐标
    • 2 添加被调用类
    • 3 添加测试类
  • 3 SpringBoot中的应用
    • 1 导入maven坐标
    • 2 添加一个管理类
    • 3 启动类上添加注解@EnableRetry
    • 4 添加测试类

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 使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解spring boot使用@Retryable来进行重处理

    前言 什么时候需要重处理? 在实际工作中,重处理是一个非常常见的场景,比如:发送消息失败,调用远程服务失败,争抢锁失败,等等,这些错误可能是因为网络波动造成的,等待过后重处理就能成功.通常来说,会用try/catch,while循环之类的语法来进行重处理,但是这样的做法缺乏统一性,并且不是很方便,要多写很多代码.然而spring-retry却可以通过注解,在不入侵原有业务逻辑代码的方式下,优雅的实现重处理功能. 思路 使用@Retryable和@Recover实现重处理,以及重处理失后的回调 实

  • SpringRetry重试框架的具体使用

    目录 一.环境搭建 二.RetryTemplate 2.1 RetryTemplate 2.2 RetryListener 2.3 回退策略 2.3.1 FixedBackOffPolicy 2.3.2 ExponentialBackOffPolicy 2.4 重试策略 2.5 RetryCallback 2.6 核心使用 三.EnableRetry 四.Retryable spring retry主要实现了重试和熔断. 不适合重试的场景: 参数校验不合法.写操作等(要考虑写是否幂等)都不适合重

  • spring-retry简单使用方法

    在分布式系统中,为了保证数据分布式事务的强一致性,大家在调用RPC接口或者发送MQ时,针对可能会出现网络抖动请求超时情况采取一下重试操作.大家用的最多的重试方式就是MQ了,但是如果你的项目中没有引入MQ,那就不方便了,本文主要介绍一下如何使用Spring Retry实现重试操作. 1. 添加maven依赖 <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-

  • Spring boot使用spring retry重试机制的方法示例

    当我们调用接口的时候由于网络原因可能失败,再尝试就成功了,这就是重试机制.非幂等的情况下要小心使用重试. tips:幂等性 HTTP/1.1中对幂等性的定义是:一次和多次请求某一个资源对于资源本身应该具有同样的结果(网络超时等问题除外).也就是说,其任意多次执行对资源本身所产生的影响均与一次执行的影响相同. 注解方式使用Spring Retry (一)Maven依赖 <!-- 重试机制 --> <dependency> <groupId>org.springframew

  • Spring Retry 重试实例详解

    spring-retry是什么? spring-retry是spring提供的一个重试框架,原本自己实现的重试机制,现在spring帮封装好提供更加好的编码体验. 重试的使用场景比较多,比如调用远程服务时,由于网络或者服务端响应慢导致调用超时,此时可以多重试几次.用定时任务也可以实现重试的效果,但比较麻烦,用Spring Retry的话一个注解搞定所有.话不多说,先看演示. 首先引入依赖 <dependency> <groupId>org.springframework.retry

  • Spring Cloud Ribbon配置详解

    本节我们主要介绍 Ribbon 的一些常用配置和配置 Ribbon 的两种方式. 常用配置 1. 禁用 Eureka 当我们在 RestTemplate 上添加 @LoadBalanced 注解后,就可以用服务名称来调用接口了,当有多个服务的时候,还能做负载均衡. 这是因为 Eureka 中的服务信息已经被拉取到了客户端本地,如果我们不想和 Eureka 集成,可以通过下面的配置方法将其禁用. # 禁用 Eureka ribbon.eureka.enabled=false 当我们禁用了 Eure

  • JSP 中Spring Bean 的作用域详解

    JSP 中Spring Bean 的作用域详解 Bean元素有一个scope属性,用于定义Bean的作用域,该属性有如下五个值: 1>singleton: 单例模式,在整个spring IOC容器中,单例模式作用域的Bean都将只生成一个实例.一般Spring容器默认Bean的作用域为singleton 2>prototype: 与singleton相反, 每次通过容器的getBean()方法获取该作用域下的Bean时都将产生一个新的Bean实例 3>request: 对于同一次Http

  • java中Spring Security的实例详解

    java中Spring Security的实例详解 spring security是一个多方面的安全认证框架,提供了基于JavaEE规范的完整的安全认证解决方案.并且可以很好与目前主流的认证框架(如CAS,中央授权系统)集成.使用spring security的初衷是解决不同用户登录不同应用程序的权限问题,说到权限包括两部分:认证和授权.认证是告诉系统你是谁,授权是指知道你是谁后是否有权限访问系统(授权后一般会在服务端创建一个token,之后用这个token进行后续行为的交互). spring

  • Spring Java-based容器配置详解

    装Java-based的配置 使用 @Import 注解 跟在Spring XML文件中使用<import>元素添加模块化的配置类似,@Import注解允许你加载其他配置类中的@Bean定义: @Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public

  • Spring AOP 基于注解详解及实例代码

    Spring AOP  基于注解详解及实例代码 1.启用spring对@AspectJ注解的支持: <beans xmlns:aop="http://www.springframework.org/schema/aop"...> <!--启动支持--> <aop:aspectj-autoproxy /> </beans> 也可以配置AnnotationAwareAspectJAutoProxyCreator Bean来启动Spring对@

  • spring结合hibernate示例详解

    单纯Hibernate程序 1.首先是导入hibernate的jar包. 2. 建立用户和用户操作记录实体,Log.Java和User.java.代码如下所示. Log.java import java.util.Date; public class Log { private int id; //日志的类别.日志一般起到一个不可否认性. //操作日志 安全日志 事件日志. private String type; private String detail; private Date time

  • 简单实现Spring的IOC原理详解

    控制反转(InversionofControl,缩写为IoC) 简单来说就是当自己需要一个对象的时候不需要自己手动去new一个,而是由其他容器来帮你提供:Spring里面就是IOC容器. 例如: 在Spring里面经常需要在Service这个装配一个Dao,一般是使用@Autowired注解:类似如下 public Class ServiceImpl{ @Autowired Dao dao; public void getData(){ dao.getData(); } 在这里未初始化Dao直接

  • Spring @Transactional工作原理详解

    本文将深入研究Spring的事务管理.主要介绍@Transactional在底层是如何工作的.之后的文章将介绍: propagation(事务传播)和isolation(隔离性)等属性的使用 事务使用的陷阱有哪些以及如何避免 JPA和事务管理 很重要的一点是JPA本身并不提供任何类型的声明式事务管理.如果在依赖注入容器之外使用JPA,事务处理必须由开发人员编程实现. UserTransaction utx = entityManager.getTransaction(); try{ utx.be

  • spring集成redis cluster详解

    客户端采用最新的jedis 2.7 1.maven依赖: <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> 2.增加spring 配置 <bean name="genericObjectPoolConfig"

随机推荐