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中可以指定需要重试的异常类型,并设置每次重试的间隔以及如果重试失败是继续重试还是熔断(停止重试)。

一、环境搭建

加入SpringRetry依赖,SpringRetry使用AOP实现,所以也需要加入AOP包

<!-- SpringRetry -->
<dependency>
   <groupId>org.springframework.retry</groupId>
   <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aspects</artifactId>
</dependency>

官方文档

二、RetryTemplate

2.1 RetryTemplate

  • RetryTemplate封装了Retry基本操作

    • org.springframework.retry.support.RetryTemplate
  • RetryTemplate中可以指定监听、回退策略、重试策略等
  • 只需要正常new RetryTemplate()即可使用

2.2 RetryListener

RetryListener指定了当执行过程中出现错误时的回调

org.springframework.retry.RetryListener

package org.springframework.retry;

public interface RetryListener {

 /**
  * 任务开始执行时调用,只调用一次
  */
 <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback);

 /**
  * 任务执行结束时(包含重试)调用,只调用一次
  */
 <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);

 /**
  * 出现错误时回调
  */
 <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);
}

配置之后在RetryTemplate中指定

2.3 回退策略

2.3.1 FixedBackOffPolicy

当出现错误时延迟多少时间继续调用

FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(1000L);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

配置之后在RetryTemplate中指定

2.3.2 ExponentialBackOffPolicy

当出现错误时第一次按照指定延迟时间延迟后按照指数进行延迟

// 指数回退(秒),第一次回退1s,第二次回退2s,第三次4秒,第四次8秒
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(1000L);
exponentialBackOffPolicy.setMultiplier(2);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

配置之后在RetryTemplate中指定

2.4 重试策略

重试策略主要指定出现错误时重试次数

// 重试策略
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);

配置之后在RetryTemplate中指定

2.5 RetryCallback

RetryCallback为retryTemplate.execute时执行的回调

public final <T, E extends Throwable> T execute(RetryCallback<T, E> retryCallback) throws E

2.6 核心使用

可以使用RetryTemplate完成简单使用
配置retryTemplate

  • 指定回退策略为ExponentialBackOffPolicy
  • 指定重试策略为SimpleRetryPolicy
  • 指定监听器RetryListener
import com.codecoord.util.PrintUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

@Configuration
public class RetryTemplateConfig {

    /**
     * 注入retryTemplate
     */
    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        /// 回退固定时间(秒)
       /* FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(1000L);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);*/

        // 指数回退(秒),第一次回退1s,第二次回退2s
        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
        exponentialBackOffPolicy.setInitialInterval(1000L);
        exponentialBackOffPolicy.setMultiplier(2);
        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

        // 重试策略
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(5);
        retryTemplate.setRetryPolicy(retryPolicy);

        // 设置监听器,open和close分别在启动和结束时执行一次
        RetryListener[] listeners = {
                new RetryListener() {
                    @Override
                    public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
                        PrintUtil.print("open");
                        return true;
                    }
                    @Override
                    public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
                            Throwable throwable) {
                        PrintUtil.print("close");
                    }
                    @Override
                    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
                            Throwable throwable) {
                        PrintUtil.print("onError");
                    }
                }
        };
        retryTemplate.setListeners(listeners);

        return retryTemplate;
    }
}

在controller中注入RetryTemplate使用,也可以是在service中

@RestController
public class SpringRetryController {
    @Resource
    private RetryTemplate retryTemplate;
    private static int count = 0;

    @RequestMapping("/retry")
    public Object retry() {
        try {
            count = 0;
            retryTemplate.execute((RetryCallback<Void, RuntimeException>) context -> {
                // 业务代码
                // ....
                // 模拟抛出异常
                ++count;
                throw new RuntimeException("抛出异常");
            });
        } catch (RuntimeException e) {
            System.out.println("Exception");
        }

        return "retry = " + count;
    }
}

访问retry接口,然后观察日志输出

18:27:20.648 - http-nio-8888-exec-1 - open
18:27:20.649 - http-nio-8888-exec-1 - retryTemplate.execute执行
18:27:20.649 - http-nio-8888-exec-1 - onError
18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute执行
18:27:21.658 - http-nio-8888-exec-1 - onError
18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute执行
18:27:23.670 - http-nio-8888-exec-1 - onError
18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute执行
18:27:27.679 - http-nio-8888-exec-1 - onError
18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute执行
18:27:35.681 - http-nio-8888-exec-1 - onError
18:27:35.681 - http-nio-8888-exec-1 - close

三、EnableRetry

@EnableRetry开启重试,在类上指定的时候方法将默认执行,重试三次
定义service,开启@EnableRetry注解和指定@Retryable,重试可以参考后面一节

import org.springframework.retry.annotation.Retryable;

public interface RetryService {

    /**
     * 重试方法调用
     */
    @Retryable
    void retryServiceCall();
}
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.stereotype.Service;

@EnableRetry
@Service
public class RetryServiceImpl implements RetryService {

    @Override
    public void retryServiceCall() {
        PrintUtil.print("方法调用..");
        throw new RuntimeException("手工异常");
    }
}

controller中注入service

@RequestMapping("/retryAnnotation")
public Object retryAnnotation() {
    retryService.retryServiceCall();
    return "retryAnnotation";
}

将会默认重试

18:46:48.721 - http-nio-8888-exec-1 - 方法调用..
18:46:49.724 - http-nio-8888-exec-1 - 方法调用..
18:46:50.730 - http-nio-8888-exec-1 - 方法调用..
java.lang.RuntimeException: 手工异常

四、Retryable

用于需要重试的方法上的注解
有以下几个属性

Retryable注解参数

  • value:指定发生的异常进行重试
  • include:和value一样,默认空,当exclude也为空时,所有异常都重试
  • exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
  • maxAttemps:重试次数,默认3
  • backoff:重试补偿机制,默认没有

@Backoff  注解 重试补偿策略

  • 不设置参数时,默认使用FixedBackOffPolicy(指定等待时间),重试等待1000ms
  • 设置delay,使用FixedBackOffPolicy(指定等待设置delay和maxDealy时,重试等待在这两个值之间均态分布)
  • 设置delay、maxDealy、multiplier,使用 ExponentialBackOffPolicy(指数级重试间隔的实现),multiplier即指定延迟倍数,比如delay=5000L,multiplier=2,则第一次重试为5秒,第二次为10秒,第三次为20秒
@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).
  * If includes is empty but excludes is not, all not excluded exceptions are retried
  * @return exception types not 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()}.
  * @date 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.
  * @date 1.2
  */
 String exceptionExpression() default "";

 /**
  * Bean names of retry listeners to use instead of default ones defined in Spring context
  * @return retry listeners bean names
  */
 String[] listeners() default {};

}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@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.
  * @date 1.2
  */
 String delayExpression() default "";

 /**
  * 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. Overrides {@link #maxDelay()}
  *
  * @return the maximum delay between retries (default 0 = ignored)
  * @date 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)
  * @date 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;
}

在需要重试的方法上配置对应的重试次数、重试异常的异常类型、设置回退延迟时间、重试策略、方法监听名称

@Component
public class PlatformClassService {
    @Retryable(
        // 重试异常的异常类型
        value = {Exception.class},
        // 最大重试次数
        maxAttempts = 5,
        // 设置回退延迟时间
        backoff = @Backoff(delay = 500),
        // 配置回调方法名称
        listeners = "retryListener"
    )
    public void call() {
        System.out.println("call...");
        throw new RuntimeException("手工异常");
    }
}
// 初始延迟2秒,然后之后验收1.5倍延迟重试,总重试次数4
@Retryable(value = {Exception.class}, maxAttempts = 4, backoff = @Backoff(delay = 2000L, multiplier = 1.5))

监听方法,在配置类中进行配置

/**
  * 注解调用
  */
@Bean
public RetryListener retryListener() {
    return new RetryListener() {
        @Override
        public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
            System.out.println("open context = " + context + ", callback = " + callback);
            // 返回true继续执行后续调用
            return true;
        }

        @Override
        public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
                                                   Throwable throwable) {
            System.out.println("close context = " + context + ", callback = " + callback);
        }
        @Override
        public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
                                                     Throwable throwable) {
            System.out.println("onError context = " + context + ", callback = " + callback);
        }
    };
}

调用服务

@RestController
public class SpringRetryController {
    @Resource
    private PlatformClassService platformClassService;

    @RequestMapping("/retryPlatformCall")
    public Object retryPlatformCall() {
        try {
            platformClassService.call();
        } catch (Exception e) {
            return "尝试调用失败";
        }
        return "retryPlatformCall";
    }
}

调用结果

到此这篇关于SpringRetry重试框架的具体使用的文章就介绍到这了,更多相关SpringRetry重试框架内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring的异常重试框架Spring Retry简单配置操作

    相关api见:点击进入 /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *

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

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

  • Spring重试支持Spring Retry的方法

    本文介绍了Spring重试支持Spring Retry的方法,分享给大家,具体如下: 第一步.引入maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> </parent> &l

  • 浅谈spring的重试机制无效@Retryable@EnableRetry

    spring-retry模块支持方法和类.接口.枚举级别的重试 方式很简单,引入pom包 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>lastest</version> </parent> <dependency> &

  • 详解重试框架Spring retry实践

    spring retry是从spring batch独立出来的一个能功能,主要实现了重试和熔断.对于重试是有场景限制的,不是什么场景都适合重试,比如参数校验不合法.写操作等(要考虑写是否幂等)都不适合重试.远程调用超时.网络突然中断可以重试.在微服务治理框架中,通常都有自己的重试与超时配置,比如dubbo可以设置retries=1,timeout=500调用失败只重试1次,超过500ms调用仍未返回则调用失败.在spring retry中可以指定需要重试的异常类型,并设置每次重试的间隔以及如果重

  • spring Retryable注解实现重试详解

    spring-boot:1.5.3.RELEASE,spring-retry-1.2.0.RELEASE 使用方法 引入pom // 版本号继承spring-boot依赖管理的pom <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <dependency>

  • 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 Boot中使用Spring-Retry重试框架的实现

    目录 Maven依赖 注解使用 开启Retry功能 注解@Retryable 注解@Recover 注解@CircuitBreaker RetryTemplate RetryTemplate配置 使用RetryTemplate RetryPolicy BackOffPolicy RetryListener 参考 Spring Retry提供了自动重新调用失败的操作的功能.这在错误可能是暂时的(例如瞬时网络故障)的情况下很有用. 从2.2.0版本开始,重试功能已从Spring Batch中撤出,成

  • Spring Boot中使用Spring Retry重试框架的操作方法

    目录 Spring Retry 在SpringBoot 中的应用 Maven依赖 注解使用 开启Retry功能 注解@Retryable 注解@Recover 注解@CircuitBreaker RetryTemplate RetryTemplate配置 使用RetryTemplate RetryPolicy BackOffPolicy RetryListener 参考 Spring Retry 在SpringBoot 中的应用 Spring Retry提供了自动重新调用失败的操作的功能.这在错

  • java 重试框架 sisyphus 入门介绍

    What is Sisyphus sisyphus综合了 spring-retry 和 gauva-retrying 的优势,使用起来也非常灵活. 为什么选择这个名字 我觉得重试做的事情和西西弗斯很相似. 一遍遍的重复,可能徒劳无功,但是乐此不疲. 人一定要想象西西弗斯的快乐.--加缪 其他原因 以前看了 java retry 的相关框架, 虽然觉得其中有很多不足之处.但是没有任何重复造轮子的冲动,觉得是徒劳无功的. 当然这段时间也看了 Netty 的接口设计,和 Hibernate-Valid

  • Java 重试框架 Sisyphus 配置的两种方式

    目录 1.函数式配置概览 1.1 默认配置 2.方法说明 2.1 condition 2.2 retryWaitContext 2.3 maxAttempt 2.4 listen 2.5 recover 2.6 callable 2.7 retryCall 3.接口的详细介绍 3.1 接口及其实现 3.2 用户自定义 3.3 sisyphus 注解 4.设计的规范 4.1 maven 引入 4.2 Retry 4.3 RetryWait 5.注解的使用 5.1 Proxy+CGLIB 5.2 S

  • Spring Retry重试框架的使用讲解

    目录 命令式 声明式(注解方式) 1. 用法 2. RetryTemplate 3. RecoveryCallback 4. Listeners 5. 声明式重试 重试的使用场景比较多,比如调用远程服务时,由于网络或者服务端响应慢导致调用超时,此时可以多重试几次.用定时任务也可以实现重试的效果,但比较麻烦,用Spring Retry的话一个注解搞定所有.话不多说,先看演示. 首先引入依赖 <dependency> <groupId>org.springframework.retry

  • SpringBoot整合spring-retry实现接口请求重试机制及注意事项

    目录 一.重试机制 二.重试机制要素 三.重试机制注意事项 四.SpringBoot整合spring-retry 1)添加依赖 2)添加@EnableRetry注解 3)添加@Retryable注解 4)Controller测试代码 5)发送请求 6)补充:@Recover 一.重试机制 由于网络不稳定或网络抖动经常会造成接口请求失败的情况,当我们再去尝试就成功了,这就是重试机制. 其主要目的就是要尽可能地提高请求成功的概率,但一般情况下,我们请求第一次失败,代码运行就抛出异常结束了,如果想再次

  • 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坐标 <dep

随机推荐