guava-retrying示例

  • 引入依赖

<dependency>
  <groupId>com.github.rholder</groupId>
  <artifactId>guava-retrying</artifactId>
  <version>2.0.0</version>
</dependency>
  • 测试用例

import com.github.rholder.retry.*;
import org.junit.Test;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class RetryTest {
    private static Integer i=0;

    @Test
    public void t1(){

        //1 任务
        Callable<Integer> callable=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                ++i;
                System.out.println("i="+i);
                if (i>=3){
                    return i;
                }
                return null;
            }
        };

        //2 构建重试器
        Retryer<Integer> retryer=RetryerBuilder.<Integer>newBuilder()
                //当返回结果为 false 时 - 执行重试
                .retryIfResult(Objects::isNull)
                //当执行核心业务逻辑抛出RuntimeException - 执行重试
                .retryIfRuntimeException()
                //自定义抛出何种异常时 - 执行重试
                .retryIfExceptionOfType(IOException.class)

                //每次重试时的时间间隔
                .withWaitStrategy(WaitStrategies.fixedWait(2L, TimeUnit.SECONDS))
                //重试次数,2次之后就不重试了
                .withStopStrategy(StopStrategies.stopAfterAttempt(2))
                //每次重试时定义一个监听器listener,监听器的逻辑可以是 "日志记录"、"做一些补偿操作"
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        System.out.println("当前是第 "+attempt.getAttemptNumber()+" 次重试");
                    }
                })

                .build();

        try {
            //3 执行任务
            Integer call = retryer.call(callable);
            System.out.println(call);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (RetryException e) {
            e.printStackTrace();
        }
    }
}

运行测试用例:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值