Guava Retrying

依赖

        <dependency>
            <groupId>com.github.rholder</groupId>
            <artifactId>guava-retrying</artifactId>
            <version>2.0.0</version>
        </dependency>

使用demo

使用Guava Retrying可以简单分为三步,(1)通过RetryerBuilder工厂类构造Retryer(2)需要重试的动作实现callable接口(3)调用call方法

RetryerBuilder


@Component
public class AppRetryerBuilder {

    public Retryer<Boolean> build() {
        return RetryerBuilder.<Boolean>newBuilder()
                //如果result为false则重试
                .retryIfResult(i -> i.equals(false))
                //如果执行中有异常则重试
                .retryIfException()
                //每次重试之间间隔三秒
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
                //最大重试次数,当达到这个次数则抛出ExecutionException异常
                .withStopStrategy(StopStrategies.stopAfterAttempt(10))
                //RetryListener可以监控多次重试过程,并可以使用attempt做一些额外的事情
                .withRetryListener(new RetryLogListener())
                .build();

    }

}

实现callable接口

        Callable<Boolean> callable = () -> {
            log.info("call times={}", times);
            times++;
            if (times == 2) {
                throw new RuntimeException();
            } else if (times == 3) {
                throw new Exception();
            } else if (times == 4) {
                return false;
            } else return times != 5;
        };

调用

        try {
            Boolean call = retryer.call(callable);//也可以不用try,call方法抛出的是运行时异常
            System.out.println(call);
        } catch (Exception e) {
            e.printStackTrace();
        }

git

https://github.com/lexiaoyao1995/retry

参考

https://www.jianshu.com/p/557eb67bb3d8

posted @ 2020-09-01 22:29  刃牙  阅读(386)  评论(0编辑  收藏  举报