重试机制Guava Retryer的使用,及其注册自定义监听器Listener

重试机制Guava Retryer的使用,及其注册自定义监听器Listener

在项目中我们一般需要远程调用其他服务,但是由于网络异常或者其他原因可能导致调用失败,此时我们就需要考虑使用重试机制,重复调用远程服务,避免由于一次调用失败导致任务执行失败的情况。

重试机制有很多的实现方式,现在介绍比较’‘优雅’'的一种重试机制:Guava Retryer

直接上代码吧

public class RetryerDemo {

    public static void main(String[] args) throws Exception{
    
        // 定义重试类Retryer
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                // 定义重试条件
                .retryIfException()  // 异常
                .retryIfRuntimeException()  // 运行时异常
                .retryIfExceptionOfType(Exception.class)
                .retryIfException(Predicates.<Throwable>equalTo(new Exception()))
                .retryIfResult(Predicates.equalTo(false))

                // 定义等待策略,即每次的间隔时间
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))

                // 定义停止策略,即重试多少次
                .withStopStrategy(StopStrategies.stopAfterAttempt(6))

                // 定义时间限制,即每次请求不超过多少时间
                .withAttemptTimeLimiter(AttemptTimeLimiters.<Boolean>fixedTimeLimit(2, TimeUnit.SECONDS))

                // 注册监听器,每次调用重试方法都会触发监听器
                .withRetryListener(new RetryerListener())

                .build();


        // 定义请求任务
        Callable<Boolean> callable = new Callable<Boolean>() {
            // 该方法为需要执行的任务,也就是需要远程调用服务的地方
            public Boolean call() throws Exception {
                return false;
            }
        };

        // 使用重试类调用任务
        retryer.call(callable);
    }
}

/*
* 监听类,每次重试都会自动触发监听器
 *		可在监听类中处理调用失败逻辑代码:如多次调用失败可发送邮件提醒等
 **/
public class RetryerListener implements RetryListener {
    public <V> void onRetry(Attempt<V> attempt) {
        System.out.println("监听器被触发");
        System.out.println("--------第" + attempt.getAttemptNumber() + "次重试---------");
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值