guava-retrying基于guava的重试模块

简介:

简介

The guava-retrying module provides a general purpose method for retrying arbitrary Java code with specific stop, retry, and exception handling capabilities that are enhanced by Guava's predicate matching.

maven依赖

<dependency>
      <groupId>com.github.rholder</groupId>
      <artifactId>guava-retrying</artifactId>
      <version>2.0.0</version>
</dependency>

使用说明

简单的demo

Callable<Boolean> callable = new Callable<Boolean>() {
    public Boolean call() throws Exception {
        return true; // do something useful here
    }
};

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
        .retryIfResult(Predicates.<Boolean>isNull())
        .retryIfExceptionOfType(IOException.class)
        .retryIfRuntimeException()
        .withStopStrategy(StopStrategies.stopAfterAttempt(3))
        .build();
try {
    retryer.call(callable);
} catch (RetryException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

首先重试的内容主体必须是一个Callable的实现,重试是根据其call方法的执行状态(异常、返回值)定制的重试策略来进行重试的。
比如上面的列子。重试者retryer由建造者RetryerBuilder创建的,RetryerBuilder提供了各种方法来定制重试策略。

根据返回是否是null来决定是否重试

.retryIfResult(Predicates.<Boolean>isNull())

根据异常类型是否是IOException来决定是否重试

.retryIfExceptionOfType(IOException.class)

多个类型的时候还可以使用Predicate

Retryer<Void> retryer1 = RetryerBuilder.<Void>newBuilder()
        .retryIfException(Predicates.or(Predicates.instanceOf(NullPointerException.class),
                                        Predicates.instanceOf(IllegalStateException.class)))
        .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 重试3次后停止
        .build();

根据异常是否是RuntimeException来决定是否重试

.retryIfRuntimeException()

设置重试的终止策略,尝试3次后终止

.withStopStrategy(StopStrategies.stopAfterAttempt(3))

除了上述重试判断外判断重试的方式与策略还有很多,比如

重试判断

返回值匹配

.retryIfResult(Predicates.containsPattern("_error$"))
.retryIfResult(Predicates.equalTo(2))

终止策略

常用的终止策略在com.github.rholder.retry.StopStrategies中。

尝试3次后终止

.withStopStrategy(StopStrategies.stopAfterAttempt(3))

30s后终止

.withStopStrategy(StopStrategies.stopAfterDelay(30,TimeUnit.SECONDS))

不终止

.withStopStrategy(StopStrategies.neverStop())

等待策略

很多场景下并不是立即重试(环境影响,立即重试的失败率依旧很高),一般会等待一段时间后继续重试。
提供了等待策略,常用策略在com.github.rholder.retry.WaitStrategies中。

比如

等待固定时间

.withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS))

每次等待时间递增

.withWaitStrategy(WaitStrategies.incrementingWait(3, TimeUnit.SECONDS,1,TimeUnit.SECONDS))

斐波那契式等待

.withWaitStrategy(WaitStrategies.fibonacciWait())

重试监听

guava-retrying提供每次重试的监听机制,每次重试后会回调注册的监听者,按顺序依次执行。

监听者必须实现RetryListener.onRetry的方法。参数attempt是每次尝试的记录。

public class MyRetryListener<Boolean> implements RetryListener {

    @Override
    public <Boolean> void onRetry(Attempt<Boolean> attempt) {

        // 第几次重试,(注意:第一次重试其实是第一次调用)
        System.out.print("[retry]time=" + attempt.getAttemptNumber());

        // 距离第一次重试的延迟
        System.out.print(",delay=" + attempt.getDelaySinceFirstAttempt());

        // 重试结果: 是异常终止, 还是正常返回
        System.out.print(",hasException=" + attempt.hasException());
        System.out.print(",hasResult=" + attempt.hasResult());

        // 是什么原因导致异常
        if (attempt.hasException()) {
            System.out.print(",causeBy=" + attempt.getExceptionCause().toString());
        } else {
            // 正常返回时的结果
            System.out.print(",result=" + attempt.getResult());
        }

        // bad practice: 增加了额外的异常处理代码
        try {
            Boolean result = attempt.get();
            System.out.print(",rude get=" + result);
        } catch (ExecutionException e) {
            System.err.println("this attempt produce exception." + e.getCause().toString());
        }

        System.out.println();
    }
}

增加监听者(可以增加多个,顺序执行)

.withRetryListener(new MyRetryListener<>())
.withRetryListener(new RetryListener() {
            @Override
            public <V> void onRetry(Attempt<V> attempt) {
                if (attempt.hasException()){
                    attempt.getExceptionCause().printStackTrace();
                }
            }
        })

核心逻辑

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

主要接口

Attempt

一次执行任务

AttemptTimeLimiter

单次任务执行时间限制(如果单次任务执行超时,则终止执行当前任务)

BlockStrategies

任务阻塞策略(通俗的讲就是当前任务执行完,下次任务还没开始这段时间做什么)

默认策略为:BlockStrategies.THREAD_SLEEP_STRATEGY 也就是调用 Thread.sleep(sleepTime);

RetryException

重试异常

RetryListener

自定义重试监听器,可以用于异步记录错误日志;

StopStrategy

停止重试策略,提供三种

  • StopAfterDelayStrategy :设定一个最长允许的执行时间比如设定最长执行10s,无论任务执行次数,只要重试的时候超出了最长时间,则任务终止,并返回重试异常RetryException
  • NeverStopStrategy :不停止,用于需要一直轮训知道返回期望结果的情况
  • StopAfterAttemptStrategy :设定最大重试次数,如果超出最大重试次数则停止重试,并返回重试异常

WaitStrategy

等待时长策略(控制时间间隔),返回结果为下次执行时长

  • FixedWaitStrategy:固定等待时长策略
  • RandomWaitStrategy:随机等待时长策略(可以提供一个最小和最大时长,等待时长为其区间随机值)
  • IncrementingWaitStrategy:递增等待时长策略(提供一个初始值和步长,等待时间随重试次数增加而增加)
  • ExponentialWaitStrategy:指数等待时长策略
  • FibonacciWaitStrategy :Fibonacci 等待时长策略
  • ExceptionWaitStrategy :异常时长等待策略
  • CompositeWaitStrategy :复合时长等待策略
目录
相关文章
|
29天前
重试工具Guava-Retryer
使用Guava Retrying库进行重试机制的示例:首先在项目中引入依赖,然后通过RetryerBuilder创建Retryer实例,设置重试条件(如:结果为null或出现特定异常),并配置停止策略和等待策略。代码示例展示了当模拟操作失败一定次数后,最终成功执行的情况。Guava Retrying提供多种重试条件,如基于异常或自定义断言,并支持配置重试次数和间隔时间。
22 5
|
缓存 Java API
Java工具篇之Guava-retry重试组件
Guava 是一组来自 Google 的核心 Java 库,其中包括新的集合类型(例如 multimap 和 multiset)、不可变集合、图形库以及用于并发、I/O、散列、缓存、原语、字符串等的实用程序!它广泛用于 Google 内部的大多数 Java 项目,也被许多其他公司广泛使用。 API 非常的简单,我们可以非常轻松的使用,来封装成我们业务中自己的组件。
849 0
|
9天前
|
消息中间件 存储 缓存
Guava的这些骚操作让我的代码量减少了50行
Guava的这些骚操作让我的代码量减少了50行
25 3
|
7月前
|
分布式计算 安全 Java
重试框架 Spring-Retry 和 Guava-Retry,你知道该怎么选吗?
一 重试框架之Spring-Retry Spring Retry 为 Spring 应用程序提供了声明性重试支持。它用于Spring批处理、Spring集成、Apache Hadoop(等等)。它主要是针对可能抛出异常的一些调用操作,进行有策略的重试
|
12月前
|
消息中间件 缓存 JavaScript
Guava的这些骚操作,让我的代码量减少了50%
Guava的这些骚操作,让我的代码量减少了50%
|
监控 Java 双11
重试利器之Guava Retrying
重试利器之Guava Retrying
472 0
重试利器之Guava Retrying
|
Java Spring
Spring Retry重试框架
实际工作中由于网络波动等原因导致代码执行失败需要重新执行,保证最终能够完成业务功能。通常来说,会用try/catch,while循环或者定时任务重处理。但是这样的做法缺乏统一性,要多写很多代码。spring-retry组件可以通过注解优雅的实现重处理功能。
537 0
|
设计模式 存储 运维
Java之Retry重试机制详解
Java之Retry重试机制详解
Java之Retry重试机制详解
|
Java 领域建模 开发者
框架来解决优雅重试-spring retry
重试的意义To make processing more robust and less prone to failure, it sometimes helps to automatically retry a failed operation, in case it might succeed on a subsequent attempt. Errors that are susceptib
2545 0
框架来解决优雅重试-spring retry
|
分布式计算 算法 Java
重试框架 Spring-Retry 和 Guava-Retry,你知道该怎么选吗?(一)
重试框架 Spring-Retry 和 Guava-Retry,你知道该怎么选吗?
重试框架 Spring-Retry 和 Guava-Retry,你知道该怎么选吗?(一)