当前位置:   article > 正文

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

guava retry

在日常开发中,尤其是在微服务盛行的时代下,我们在调用外部接口时,经常会因为第三方接口超时、限流等问题从而造成接口调用失败,那么此时我们通常会对接口进行重试,那么问题来了,如何重试呢?该重试几次呢?如果要设置重试时间超过多长时间后还不成功就不重试了该怎么做呢?所幸guava-retrying为我们提供了强大而简单易用的重试框架guava-retrying。

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

一、pom依赖

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

二、使用示例

我们可以通过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.

三、重试时机

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

1. 根据异常进行重试

2. 根据返回结果进行重试

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

四、停止重试策略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. }

1. NeverStopStrategy

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

  1. @Override
  2. public boolean shouldStop(Attempt failedAttempt) {
  3. return false;
  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. }

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. }

五、重试间隔策略、重试阻塞策略

这两个策略放在一起说,它们合起来的作用就是用来控制重试任务之间的间隔时间,以及如何任务在等待时间间隔时如何阻塞。也就是说WaitStrategy决定了重试任务等待多久后进行下一次任务的执行,BlockStrategy用来决定任务如何等待。它们两的策略工厂分别为com.github.rholder.retry.WaitStrategies和BlockStrategies。

1.BlockStrategy

(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. }

2. WaitStrategy

(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时长。

(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. }

(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. }

() 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) CompositeWaitStrategy

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

  1. private static final class CompositeWaitStrategy implements WaitStrategy {
  2. private final List<WaitStrategy> waitStrategies;
  3. public CompositeWaitStrategy(List<WaitStrategy> 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. }

(6) FibonacciWaitStrategy

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

(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. }

六、重试监听器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次执行

七、重试原理

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

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

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

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

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

八、总结

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/828906
推荐阅读
相关标签
  

闽ICP备14008679号