关于Guava-Retry重试工具的使用_guava retry demo-程序员宅基地

技术标签: java  后端  技能点  开发语言  


官网地址:

https://github.com/rholder/guava-retrying

https://codechina.csdn.net/mirrors/rholder/guava-retrying?utm_source=csdn_github_accelerator

1 guava-retry的简介

在日常的一些场景中, 很多需要进行重试的操作.查询资料Guava-Retry工具对于重试操作效果比较好.

Guava retryer是一个基于Guava,提供重试机制的库,是通过定义重试者角色来包装正常逻辑重试,支持重试次数和重试频度控制,能够兼容支持多个异常或者自定义实体对象的重试源定义,让重试功能有更多的灵活性, 而且也是线程安全的,入口调用逻辑采用的是java.util.concurrent.Callable的call方法.

2 guava-retry的使用

1 导入maven依赖
  <!-- https://mvnrepository.com/artifact/com.github.rholder/guava-retrying -->
    <dependency>
        <groupId>com.github.rholder</groupId>
        <artifactId>guava-retrying</artifactId>
        <version>2.0.0</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 GuavaRetryTest {
    

    public static void main(String[] args) {
    
        Boolean result = false;
        // RetryerBuilder 构建重试实例对象
        // 1 可以设置重试源且可以支持多个重试源
        // 2 可以设置根据结果重试
        // 3 可以配置等待时间间隔
        // 4 可以配置重试次数或重试超时时间
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfExceptionOfType(RemoteAccessException.class)//设置异常重试源
                .retryIfException()
                .retryIfResult(res -> false) //设置根据结果重试
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) //设置等待间隔时间
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)) //设置最大重试次数
                .withRetryListener(new RetryListener() {
    
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
    
                        log.info("第【{}】次调用失败", attempt.getAttemptNumber());
                    }
                })
                .build();

        try {
    
            result = retryer.call(new Callable<Boolean>() {
    
                @Override
                public Boolean call() throws Exception {
    
                    return RetryDemo.retryMethod(110);
                }
            });

            // 上述可以简化为
//            result = retryer.call(() -> RetryDemo.retryMethod(110));

        } catch (Exception e) {
    
            e.printStackTrace();
            log.info("超时三次错误,{}", e.getMessage());
        }

        System.out.println("方法调用返回状态= " + result);
    }
}    

说明:

RetryerBuilder类是一个工厂建造者,可以设置多个重试源,可以设置重试次数和重试超时时间等,创建重试者Retryer对象.

RetryerBuilder部分源码:

public class RetryerBuilder<V> {
    
    // 单次任务执行时间限制
    private AttemptTimeLimiter<V> attemptTimeLimiter;
    // 停止策略
    private StopStrategy stopStrategy;
    // 等待策略
    private WaitStrategy waitStrategy;
    // 阻塞策略
    private BlockStrategy blockStrategy;
    // 重试源 支持Exception异常对象和自定义断言对象
    private Predicate<Attempt<V>> rejectionPredicate = Predicates.alwaysFalse();
    // 重试监听
    private List<RetryListener> listeners = new ArrayList<RetryListener>();

    private RetryerBuilder() {
    
    }

    // new一个RetryerBuilder对象
    /**
     * Constructs a new builder
     *
     * @param <V> result of a {@link Retryer}'s call, the type of the call return value
     * @return the new builder
     */
    public static <V> RetryerBuilder<V> newBuilder() {
    
        return new RetryerBuilder<V>();
    }
    
    
    // 创建一个Retryer对象
    /**
     * Builds the retryer.
     *
     * @return the built retryer.
     */
    public Retryer<V> build() {
    
        AttemptTimeLimiter<V> theAttemptTimeLimiter = attemptTimeLimiter == null ? AttemptTimeLimiters.<V>noTimeLimit() : attemptTimeLimiter;
        StopStrategy theStopStrategy = stopStrategy == null ? StopStrategies.neverStop() : stopStrategy;
        WaitStrategy theWaitStrategy = waitStrategy == null ? WaitStrategies.noWait() : waitStrategy;
        BlockStrategy theBlockStrategy = blockStrategy == null ? BlockStrategies.threadSleepStrategy() : blockStrategy;

        return new Retryer<V>(theAttemptTimeLimiter, theStopStrategy, theWaitStrategy, theBlockStrategy, rejectionPredicate, listeners);
    }
    
    // ...
}    

Retryer部分源码:

public final class Retryer<V> {
    
    // 停止策略
    private final StopStrategy stopStrategy;
    // 等待策略
    private final WaitStrategy waitStrategy;
    // 阻塞策略
    private final BlockStrategy blockStrategy;
    // 单次任务执行时间限制
    private final AttemptTimeLimiter<V> attemptTimeLimiter;
    // 重试源 支持Exception异常对象和自定义断言对象
    private final Predicate<Attempt<V>> rejectionPredicate;
    // 重试监听
    private final Collection<RetryListener> listeners;
    
    
    // RetryerBuilder建造者中build方法被使用
    /**
     * Constructor
     *
     * @param attemptTimeLimiter to prevent from any single attempt from spinning infinitely
     * @param stopStrategy       the strategy used to decide when the retryer must stop retrying
     * @param waitStrategy       the strategy used to decide how much time to sleep between attempts
     * @param blockStrategy      the strategy used to decide how to block between retry attempts; eg, Thread#sleep(), latches, etc.
     * @param rejectionPredicate the predicate used to decide if the attempt must be rejected
     *                           or not. If an attempt is rejected, the retryer will retry the call, unless the stop
     *                           strategy indicates otherwise or the thread is interrupted.
     * @param listeners          collection of retry listeners
     */
    @Beta
    public Retryer(@Nonnull AttemptTimeLimiter<V> attemptTimeLimiter,
                   @Nonnull StopStrategy stopStrategy,
                   @Nonnull WaitStrategy waitStrategy,
                   @Nonnull BlockStrategy blockStrategy,
                   @Nonnull Predicate<Attempt<V>> rejectionPredicate,
                   @Nonnull Collection<RetryListener> listeners) {
    
        Preconditions.checkNotNull(attemptTimeLimiter, "timeLimiter may not be null");
        Preconditions.checkNotNull(stopStrategy, "stopStrategy may not be null");
        Preconditions.checkNotNull(waitStrategy, "waitStrategy may not be null");
        Preconditions.checkNotNull(blockStrategy, "blockStrategy may not be null");
        Preconditions.checkNotNull(rejectionPredicate, "rejectionPredicate may not be null");
        Preconditions.checkNotNull(listeners, "listeners may not null");

        this.attemptTimeLimiter = attemptTimeLimiter;
        this.stopStrategy = stopStrategy;
        this.waitStrategy = waitStrategy;
        this.blockStrategy = blockStrategy;
        this.rejectionPredicate = rejectionPredicate;
        this.listeners = listeners;
    }
    
    // 线程安全调用重试方法
    /**
     * Executes the given callable. If the rejection predicate
     * accepts the attempt, the stop strategy is used to decide if a new attempt
     * must be made. Then the wait strategy is used to decide how much time to sleep
     * and a new attempt is made.
     *
     * @param callable the callable task to be executed
     * @return the computed result of the given callable
     * @throws ExecutionException if the given callable throws an exception, and the
     *                            rejection predicate considers the attempt as successful. The original exception
     *                            is wrapped into an ExecutionException.
     * @throws RetryException     if all the attempts failed before the stop strategy decided
     *                            to abort, or the thread was interrupted. Note that if the thread is interrupted,
     *                            this exception is thrown and the thread's interrupt status is set.
     */
    public V call(Callable<V> callable) throws ExecutionException, RetryException {
    
        long startTime = System.nanoTime();
        for (int attemptNumber = 1; ; attemptNumber++) {
    
            Attempt<V> attempt;
            try {
    
                V result = attemptTimeLimiter.call(callable);
                attempt = new ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
            } catch (Throwable t) {
    
                attempt = new ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
            }

            for (RetryListener listener : listeners) {
    
                listener.onRetry(attempt);
            }

            if (!rejectionPredicate.apply(attempt)) {
    
                return attempt.get();
            }
            if (stopStrategy.shouldStop(attempt)) {
    
                throw new RetryException(attemptNumber, attempt);
            } else {
    
                long sleepTime = waitStrategy.computeSleepTime(attempt);
                try {
    
                    blockStrategy.block(sleepTime);
                } catch (InterruptedException e) {
    
                    Thread.currentThread().interrupt();
                    throw new RetryException(attemptNumber, attempt);
                }
            }
        }
    }
       
}    

3 总结

Guava-Retry, 是一个非常灵活简单上手的工具. 可以完好的把重试功能和业务逻辑解耦, 不但支持多种设置, 如多异常判断,重试次数,重试时间,以及每次重试方法时的监听.并且是属于线程安全的, 在并发的场景下也能稳定支持.

参考资料:

https://blog.csdn.net/zzzgd_666/article/details/84377962

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ABestRookie/article/details/121238468

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法