重试工具Guava-Retryer

218 阅读1分钟

1、怎么用:
1、1引入pom文件

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

1.2

package com.wosai.upaysp.biz.guavaRetrying;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class RetryTest {
    private static final Logger logger = LoggerFactory.getLogger(RetryTest.class);
    public static void main(String[] args) {
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(Predicates.<Boolean>isNull())// 设置自定义段元重试源
                .retryIfExceptionOfType(Exception.class)// 设置异常重试源
//                .retryIfRuntimeException()// 设置异常重试源
                .withStopStrategy(StopStrategies.stopAfterAttempt(7))// 设置重试7次,同样可以设置重试超时时间
                .withWaitStrategy(WaitStrategies.fixedWait(2L, TimeUnit.SECONDS))// 设置每次重试间隔,5秒
                .build();
        try {
            retryer.call(new Callable<Boolean>() {
                int i = 0;
                @Override
                public Boolean call() throws Exception {
                    i++;
                    logger.info("第{}次执行!", i);
                    // do something
                    if (i < 6) {// 模拟错2次
                        logger.info("模拟执行失败!");
                        throw new IOException("异常");
                    }
                    logger.info("模拟执行成功!");
                    return true;
                }
            });
        } catch (Exception e) {
            logger.info("超过重试次数", e);
        }
    }
}

结果如下,可以看到错误重试,正确执行了一次
图片

图片
编辑

2、简介:

• RetryerBuilder是一个factory创建者,可以定制设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔,创建重试者Retryer实例。
• RetryerBuilder的重试源支持Exception异常对象 和自定义断言对象,通过retryIfException 和retryIfResult设置,同时支持多个且能兼容。
• retryIfException,抛出runtime异常、checked异常时都会重试,但是抛出error不会重试。
• retryIfRuntimeException只会在抛runtime异常的时候才重试,checked异常和error都不重试。
• retryIfExceptionOfType允许我们只在发生特定异常的时候才重试,比如NullPointerException和IllegalStateException都属于runtime异常,也包括自定义的error
其他的功能还未用过,之后再探究下,知道这个工具要感谢一位小伙伴的分享!