• 使用 Guava-Retry 优雅的实现重处理


    guava-retrying是谷歌的Guava库的一个小扩展,允许为任意函数调用创建可配置的重试策略,比如与正常运行时间不稳定的远程服务对话的函数调用。

    1. pom依赖

    1.     <dependency>
    2.       <groupId>com.github.rholder</groupId>
    3.       <artifactId>guava-retrying</artifactId>
    4.       <version>2.0.0</version>
    5.     </dependency>

    2. 使用示例

    我们可以通过RetryerBuilder来构造一个重试器,通过RetryerBuilder可以设置什么时候需要重试(即重试时机)、停止重试策略、失败等待时间间隔策略、任务执行时长限制策略

    先看一个简单的例子:

    1.     private int invokeCount = 0;
    2.     public int realAction(int num) {
    3.         invokeCount++;
    4.         System.out.println(String.format("当前执行第 %d 次,num:%d", invokeCount, num));
    5.         if (num <= 0) {
    6.             throw new IllegalArgumentException();
    7.         }
    8.         return num;
    9.     }
    10.     @Test
    11.     public void guavaRetryTest001() {
    12.         Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
    13.             // 非正数进行重试
    14.             .retryIfRuntimeException()
    15.             // 偶数则进行重试
    16.             .retryIfResult(result -> result % 2 == 0)
    17.             // 设置最大执行次数3
    18.             .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
    19.         try {
    20.             invokeCount=0;
    21.             retryer.call(() -> realAction(0));
    22.         } catch (Exception e) {
    23.             System.out.println("执行0,异常:" + e.getMessage());
    24.         }
    25.         try {
    26.             invokeCount=0;
    27.             retryer.call(() -> realAction(1));
    28.         } catch (Exception e) {
    29.             System.out.println("执行1,异常:" + e.getMessage());
    30.         }
    31.         try {
    32.             invokeCount=0;
    33.             retryer.call(() -> realAction(2));
    34.         } catch (Exception e) {
    35.             System.out.println("执行2,异常:" + e.getMessage());
    36.         }
    37.     }

    输出:

    1. 当前执行第 1 次,num:0
    2. 当前执行第 2 次,num:0
    3. 当前执行第 3 次,num:0
    4. 执行0,异常:Retrying failed to complete successfully after 3 attempts.
    5. 当前执行第 1 次,num:1
    6. 当前执行第 1 次,num:2
    7. 当前执行第 2 次,num:2
    8. 当前执行第 3 次,num:2
    9. 执行2,异常:Retrying failed to complete successfully after 3 attempts.

    3. 重试时机

    RetryerBuilder的retryIfXXX()方法用来设置**在什么情况下进行重试,总体上可以分为根据执行异常进行重试根据方法执行结果进行重试两类。关注公众号:“码猿技术专栏”,回复关键词:“1111” 获取阿里内部Java调优手册

    3.1 根据异常进行重试

    方法描述
    retryIfException()当方法执行抛出异常 isAssignableFrom Exception.class 时重试
    retryIfRuntimeException()当方法执行抛出异常 isAssignableFrom RuntimeException.class 时重试
    retryIfException(Predicate exceptionPredicate)这里当发生异常时,会将异常传递给exceptionPredicate,那我们就可以通过传入的异常进行更加自定义的方式来决定什么时候进行重试
    retryIfExceptionOfType(Class exceptionClass)当方法执行抛出异常 isAssignableFrom 传入的exceptionClass 时重试

    3.2 根据返回结果进行重试

    retryIfResult(@Nonnull Predicate resultPredicate) 这个比较简单,当我们传入的resultPredicate返回true时则进行重试

    4. 停止重试策略StopStrategy

    停止重试策略用来决定什么时候不进行重试,其接口com.github.rholder.retry.StopStrategy,停止重试策略的实现类均在com.github.rholder.retry.StopStrategies中,它是一个策略工厂类。

    1. public interface StopStrategy {
    2.     /**
    3.      * Returns <code>true</code> if the retryer should stop retrying.
    4.      *
    5.      * @param failedAttempt the previous failed {@code Attempt}
    6.      * @return <code>true</code> if the retryer must stop<code>false</code> otherwise
    7.      */
    8.     boolean shouldStop(Attempt failedAttempt);
    9. }

    4.1 NeverStopStrategy

    此策略将永远重试,永不停止,查看其实现类,直接返回了false

    1. @Override
    2. public boolean shouldStop(Attempt failedAttempt) {
    3.  return false;
    4. }

    4.2 StopAfterAttemptStrategy

    当执行次数到达指定次数之后停止重试,查看其实现类:

    1.     private static final class StopAfterAttemptStrategy implements StopStrategy {
    2.         private final int maxAttemptNumber;
    3.         public StopAfterAttemptStrategy(int maxAttemptNumber) {
    4.             Preconditions.checkArgument(maxAttemptNumber >= 1"maxAttemptNumber must be >= 1 but is %d", maxAttemptNumber);
    5.             this.maxAttemptNumber = maxAttemptNumber;
    6.         }
    7.         @Override
    8.         public boolean shouldStop(Attempt failedAttempt) {
    9.             return failedAttempt.getAttemptNumber() >= maxAttemptNumber;
    10.         }
    11.     }

    4.3 StopAfterDelayStrategy

    当距离方法的第一次执行超出了指定的delay时间时停止,也就是说一直进行重试,当进行下一次重试的时候会判断从第一次执行到现在的所消耗的时间是否超过了这里指定的delay时间,查看其实现:

    1.    private static final class StopAfterAttemptStrategy implements StopStrategy {
    2.         private final int maxAttemptNumber;
    3.         public StopAfterAttemptStrategy(int maxAttemptNumber) {
    4.             Preconditions.checkArgument(maxAttemptNumber >= 1"maxAttemptNumber must be >= 1 but is %d", maxAttemptNumber);
    5.             this.maxAttemptNumber = maxAttemptNumber;
    6.         }
    7.         @Override
    8.         public boolean shouldStop(Attempt failedAttempt) {
    9.             return failedAttempt.getAttemptNumber() >= maxAttemptNumber;
    10.         }
    11.     }

    5. 重试间隔策略、重试阻塞策略

    这两个策略放在一起说,它们合起来的作用就是用来控制重试任务之间的间隔时间,以及如何任务在等待时间间隔时如何阻塞。也就是说WaitStrategy决定了重试任务等待多久后进行下一次任务的执行,BlockStrategy用来决定任务如何等待。它们两的策略工厂分别为com.github.rholder.retry.WaitStrategies和BlockStrategies。关注公众号:“码猿技术专栏”,回复关键词:“1111” 获取阿里内部Java调优手册

    5.1 BlockStrategy

    5.1.1 ThreadSleepStrategy

    这个是BlockStrategies,决定如何阻塞任务,其主要就是通过**Thread.sleep()**来进行阻塞的,查看其实现:

    1.     @Immutable
    2.     private static class ThreadSleepStrategy implements BlockStrategy {
    3.         @Override
    4.         public void block(long sleepTime) throws InterruptedException {
    5.             Thread.sleep(sleepTime);
    6.         }
    7.     }

    5.2 WaitStrategy

    5.2.1 IncrementingWaitStrategy

    该策略在决定任务间隔时间时,返回的是一个递增的间隔时间,即每次任务重试间隔时间逐步递增,越来越长,查看其实现:

    1.     private static final class IncrementingWaitStrategy implements WaitStrategy {
    2.         private final long initialSleepTime;
    3.         private final long increment;
    4.         public IncrementingWaitStrategy(long initialSleepTime,
    5.                                         long increment) {
    6.             Preconditions.checkArgument(initialSleepTime >= 0L"initialSleepTime must be >= 0 but is %d", initialSleepTime);
    7.             this.initialSleepTime = initialSleepTime;
    8.             this.increment = increment;
    9.         }
    10.         @Override
    11.         public long computeSleepTime(Attempt failedAttempt) {
    12.             long result = initialSleepTime + (increment * (failedAttempt.getAttemptNumber() - 1));
    13.             return result >= 0L ? result : 0L;
    14.         }
    15.     }

    该策略输入一个起始间隔时间值和一个递增步长,然后每次等待的时长都递增increment时长。

    5.2.2 RandomWaitStrategy

    顾名思义,返回一个随机的间隔时长,我们需要传入的就是一个最小间隔和最大间隔,然后随机返回介于两者之间的一个间隔时长,其实现为:

    1.     private static final class RandomWaitStrategy implements WaitStrategy {
    2.         private static final Random RANDOM = new Random();
    3.         private final long minimum;
    4.         private final long maximum;
    5.         public RandomWaitStrategy(long minimum, long maximum) {
    6.             Preconditions.checkArgument(minimum >= 0"minimum must be >= 0 but is %d", minimum);
    7.             Preconditions.checkArgument(maximum > minimum, "maximum must be > minimum but maximum is %d and minimum is", maximum, minimum);
    8.             this.minimum = minimum;
    9.             this.maximum = maximum;
    10.         }
    11.         @Override
    12.         public long computeSleepTime(Attempt failedAttempt) {
    13.             long t = Math.abs(RANDOM.nextLong()) % (maximum - minimum);
    14.             return t + minimum;
    15.         }
    16.     }

    5.2.3 FixedWaitStrategy

    该策略是返回一个固定时长的重试间隔。查看其实现:

    1.     private static final class FixedWaitStrategy implements WaitStrategy {
    2.         private final long sleepTime;
    3.         public FixedWaitStrategy(long sleepTime) {
    4.             Preconditions.checkArgument(sleepTime >= 0L"sleepTime must be >= 0 but is %d", sleepTime);
    5.             this.sleepTime = sleepTime;
    6.         }
    7.         @Override
    8.         public long computeSleepTime(Attempt failedAttempt) {
    9.             return sleepTime;
    10.         }
    11.     }

    5.2.4 ExceptionWaitStrategy

    该策略是由方法执行异常来决定是否重试任务之间进行间隔等待,以及间隔多久。

    1.     private static final class ExceptionWaitStrategy<T extends Throwable> implements WaitStrategy {
    2.         private final Class<T> exceptionClass;
    3.         private final Function<T, Long> function;
    4.         public ExceptionWaitStrategy(@Nonnull Class<T> exceptionClass, @Nonnull Function<T, Long> function) {
    5.             this.exceptionClass = exceptionClass;
    6.             this.function = function;
    7.         }
    8.         @SuppressWarnings({"ThrowableResultOfMethodCallIgnored""ConstantConditions""unchecked"})
    9.         @Override
    10.         public long computeSleepTime(Attempt lastAttempt) {
    11.             if (lastAttempt.hasException()) {
    12.                 Throwable cause = lastAttempt.getExceptionCause();
    13.                 if (exceptionClass.isAssignableFrom(cause.getClass())) {
    14.                     return function.apply((T) cause);
    15.                 }
    16.             }
    17.             return 0L;
    18.         }
    19.     }

    5.2.5 CompositeWaitStrategy

    这个没啥好说的,顾名思义,就是一个策略的组合,你可以传入多个WaitStrategy,然后所有WaitStrategy返回的间隔时长相加就是最终的间隔时间。查看其实现:

    1.    private static final class CompositeWaitStrategy implements WaitStrategy {
    2.         private final List waitStrategies;
    3.         public CompositeWaitStrategy(List waitStrategies) {
    4.             Preconditions.checkState(!waitStrategies.isEmpty(), "Need at least one wait strategy");
    5.             this.waitStrategies = waitStrategies;
    6.         }
    7.         @Override
    8.         public long computeSleepTime(Attempt failedAttempt) {
    9.             long waitTime = 0L;
    10.             for (WaitStrategy waitStrategy : waitStrategies) {
    11.                 waitTime += waitStrategy.computeSleepTime(failedAttempt);
    12.             }
    13.             return waitTime;
    14.         }
    15.     }

    5.2.6 FibonacciWaitStrategy

    这个策略与IncrementingWaitStrategy有点相似,间隔时间都是随着重试次数的增加而递增的,不同的是,FibonacciWaitStrategy是按照斐波那契数列来进行计算的,使用这个策略时,我们需要传入一个乘数因子和最大间隔时长,其实现就不贴了

    5.2.7 ExponentialWaitStrategy

    这个与IncrementingWaitStrategy、FibonacciWaitStrategy也类似,间隔时间都是随着重试次数的增加而递增的,但是该策略的递增是呈指数级递增。查看其实现:

    1.     private static final class ExponentialWaitStrategy implements WaitStrategy {
    2.         private final long multiplier;
    3.         private final long maximumWait;
    4.         public ExponentialWaitStrategy(long multiplier,
    5.                                        long maximumWait) {
    6.             Preconditions.checkArgument(multiplier > 0L"multiplier must be > 0 but is %d", multiplier);
    7.             Preconditions.checkArgument(maximumWait >= 0L"maximumWait must be >= 0 but is %d", maximumWait);
    8.             Preconditions.checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier);
    9.             this.multiplier = multiplier;
    10.             this.maximumWait = maximumWait;
    11.         }
    12.         @Override
    13.         public long computeSleepTime(Attempt failedAttempt) {
    14.             double exp = Math.pow(2, failedAttempt.getAttemptNumber());
    15.             long result = Math.round(multiplier * exp);
    16.             if (result > maximumWait) {
    17.                 result = maximumWait;
    18.             }
    19.             return result >= 0L ? result : 0L;
    20.         }
    21.     }

    6. 重试监听器RetryListener

    当发生重试时,将会调用RetryListener的onRetry方法,此时我们可以进行比如记录日志等额外操作。

    1.     public int realAction(int num) {
    2.         if (num <= 0) {
    3.             throw new IllegalArgumentException();
    4.         }
    5.         return num;
    6.     }
    7.     @Test
    8.     public void guavaRetryTest001() throws ExecutionException, RetryException {
    9.         Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder().retryIfException()
    10.             .withRetryListener(new MyRetryListener())
    11.             // 设置最大执行次数3
    12.             .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();
    13.         retryer.call(() -> realAction(0));
    14.     }
    15.     private static class MyRetryListener implements RetryListener {
    16.         @Override
    17.         public <V> void onRetry(Attempt<V> attempt) {
    18.             System.out.println("第" + attempt.getAttemptNumber() + "次执行");
    19.         }
    20.     }

    输出:

    1. 1次执行
    2. 2次执行
    3. 3次执行

    7. 重试原理

    其实到这一步之后,实现原理大概就很清楚了,就是由上述各种策略配合从而达到了非常灵活的重试机制。在这之前我们看一个上面没说的东东-Attempt

    1. public interface Attempt<V> {
    2.     public V get() throws ExecutionException;
    3.     public boolean hasResult();
    4.     
    5.     public boolean hasException();
    6.     public V getResult() throws IllegalStateException;
    7.     public Throwable getExceptionCause() throws IllegalStateException;
    8.     public long getAttemptNumber();
    9.     public long getDelaySinceFirstAttempt();
    10. }

    通过接口方法可以知道Attempt这个类包含了任务执行次数、任务执行异常、任务执行结果、以及首次执行任务至今的时间间隔,那么我们后续的不管重试时机、还是其他策略都是根据此值来决定。

    接下来看关键执行入口Retryer##call:

    1.     public V call(Callable<V> callable) throws ExecutionException, RetryException {
    2.         long startTime = System.nanoTime();
    3.         
    4.         // 执行次数从1开始
    5.         for (int attemptNumber = 1; ; attemptNumber++) {
    6.             Attempt<V> attempt;
    7.             try {
    8.                 // 尝试执行
    9.                 V result = attemptTimeLimiter.call(callable);
    10.                 
    11.                 // 执行成功则将结果封装为ResultAttempt
    12.                 attempt = new Retryer.ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
    13.             } catch (Throwable t) {
    14.                 // 执行异常则将结果封装为ExceptionAttempt
    15.                 attempt = new Retryer.ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
    16.             }
    17.             // 这里将执行结果传给RetryListener做一些额外事情
    18.             for (RetryListener listener : listeners) {
    19.                 listener.onRetry(attempt);
    20.             }
    21.             // 这个就是决定是否要进行重试的地方,如果不进行重试直接返回结果,执行成功就返回结果,执行失败就返回异常
    22.             if (!rejectionPredicate.apply(attempt)) {
    23.                 return attempt.get();
    24.             }
    25.             
    26.             // 到这里,说明需要进行重试,则此时先决定是否到达了停止重试的时机,如果到达了则直接返回异常
    27.             if (stopStrategy.shouldStop(attempt)) {
    28.                 throw new RetryException(attemptNumber, attempt);
    29.             } else {
    30.                 // 决定重试时间间隔
    31.                 long sleepTime = waitStrategy.computeSleepTime(attempt);
    32.                 try {
    33.                     // 进行阻塞
    34.                     blockStrategy.block(sleepTime);
    35.                 } catch (InterruptedException e) {
    36.                     Thread.currentThread().interrupt();
    37.                     throw new RetryException(attemptNumber, attempt);
    38.                 }
    39.             }
    40.         }

    8. 总结

    通篇下来可以看到其实核心实现并不难,但是此框架通过建造者模式和策略模式组合运用,提供了十分清晰明了且灵活的重试机制,其设计思路还是值得借鉴学习!

  • 相关阅读:
    SHEIN推出自主运营+代运营多模式,助力卖家实现快速增长
    K8S的安全机制
    Node.js 框架 star 星数量排名——NestJs跃居第二
    家里照片都看不清了怎么办?教你三招修复旧照片
    我的Go gRPC之旅、01 初识gRPC,感受gRPC的强大魅力
    10000阅读量感言
    基于JAVA课程网站设计计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    【嵌入式开发 Linux 常用命令系列 9 -- linux系统终端命令提示符设置(PS1)】
    【C++】STL详解(九)—— set、map、multiset、multimap的介绍及使用
    MyBatis的逆向工程
  • 原文地址:https://blog.csdn.net/AS011x/article/details/126517681