guava的retry工具类

        通常我们在访问第三方接口时,由于网络抖动或其他原因需要重试,spring和guava都提供了retry的工具。下面简单介绍一下guava的retry,相比较spring的retry,使用起来更加的简单便捷。

       首先我们需要实例化一个重试器

eg:

/**
     * 创建一个重试器,重试器执行的方法
     */
    private static Retryer retryer = RetryerBuilder.newBuilder()
            // 出现异常时,会重试
            .retryIfException()
            // 失败后,隔2秒后重试
            .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))
            // 重试3次后,仍未成功,就不再重试
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            .build();

 通过构造方法即可看出各参数的含义。       

/**
     * Constructor
     *
     * @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 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.
     */
    public Retryer(@Nonnull StopStrategy stopStrategy,
                   @Nonnull WaitStrategy waitStrategy,
                   @Nonnull Predicate<Attempt<V>> rejectionPredicate) {

        this(AttemptTimeLimiters.<V>noTimeLimit(), stopStrategy, waitStrategy, BlockStrategies.threadSleepStrategy(), rejectionPredicate);
    }

 然后使用时,直接通过retryer.call(() -> //TODO业务逻辑)即可。

/**
     * 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);
                }
            }
        }
    }

  使用起来非常的简单,参照着就可以很容易实现一个重试的功能。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Guava RetryGuava库中提供的一种重试机制。它允许你在方法执行失败时自动进行重试,以增加方法的可靠性和稳定性。 使用Guava Retry,你可以定义重试策略,包括重试的最大次数、重试间隔等。当方法执行失败时,Retry会根据定义的策略自动进行重试,直到方法功执行或达到最大重试次数。 下面是一个使用Guava Retry的示例代码: ```java import com.google.common.base.Predicates; import com.google.common.base.Throwables; import import com.google.common.util.concurrent.RateLimiter; import import com.google.common.util.concurrent.Retryer; import import com.google.common.util.concurrent.SimpleTimeLimiter; import import com.google.common.util.concurrent.TimeLimiter; import import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; public class GuavaRetryExample { public static void main(String[] args) { // 创建一个重试器 Retryer<Boolean> retryer = Retryer.newBuilder() .retryIfResult(Predicates.isNull()) .retryIfException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); // 定义需要重试的方法 Callable<Boolean> callable = new Callable<Boolean>() { public Boolean call() throws Exception { // 这里可以放置需要重试的逻辑 // 如果方法执行失败,抛出异常 throw new Exception("Method execution failed"); } }; try { // 使用重试器来执行方法 Boolean result = retryer.call(callable); System.out.println("Method execution result: " + result); } catch (ExecutionException e) { // 打印重试失败的异常信息 System.out.println("Retry failed: " + Throwables.getRootCause(e)); } catch (RetryException e) { // 打印重试异常信息 System.out.println("Retry failed: " + e.getMessage()); } } } ``` 在上述示例中,我们创建了一个重试器,并定义了重试的条件和策略。然后,我们通过`retryer.call(callable)`来执行需要重试的方法。如果方法执行功,将会返回执行结果;如果方法执行失败,将会抛出重试异常。 需要注意的是,Guava Retry并不会自动处理所有型的异常。如果你希望在特定的异常情况下进行重试,可以使用`retryIfException`方法,并指定需要重试的异常型。 这就是Guava Retry的简单介绍和示例代码,希望对你有帮助!如果还有其他问题,请继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值