文章目录

  • 1、重试
  • 1.1 重试作用
  • 2、重试的三种方法
  • 2.1 java retry
  • 2.2 spring retry
  • 2.3 guava-retrying
  • 2.3.1 重试源
  • 2.3.2 自定义重试监听器 RetryListener
  • 2.3.3 停止重试策略 StopStrategy
  • 2.3.4 等待时长策略(控制时间间隔)withWaitStrategy
  • 3、guava-retrying demo
  • 3.1 Maven依赖
  • 3.2 项目结构


1、重试

1.1 重试作用

对于重试是有场景限制的,不是什么场景都适合重试,比如参数校验不合法、写操作等(要考虑写是否幂等)都不适合重试。

远程调用超时、网络突然中断可以重试。在微服务治理框架中,通常都有自己的重试与超时配置,比如dubbo可以设置retries=1、timeout=500,表示调用失败只重试1次,超过500ms调用仍未返回,则调用失败。

外部 RPC 调用,或者数据入库等操作,如果一次操作失败,可以进行多次重试,提高调用成功的可能性。

2、重试的三种方法

2.1 java retry

2.2 spring retry

2.3 guava-retrying

RetryerBuilder 是一个 factory 创建者,可以定制设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔创建重试者Retryer实例

2.3.1 重试源

RetryerBuilder 的重试源支持 Exception 异常对象和自定义断言对象,通过retryIfException 和 retryIfResult 设置,同时支持多个且能兼容

  • retryIfException,抛出 runtime 异常、checked 异常时都会重试,但是抛出 error 不会重试。
  • retryIfRuntimeException 只会在抛 runtime 异常的时候才重试,checked 异常和error 都不重试。
  • retryIfExceptionOfType 允许我们只在发生特定异常的时候才重试,比如NullPointerException 和 IllegalStateException 都属于 runtime 异常,也包括自定义的error。或通过Predicate实现。
  • .retryIfExceptionOfType(Error.class) // 只在抛出error时重试
  • .retryIfExceptionOfType(IllegalStateException.class)
  • .retryIfExceptionOfType(NullPointerException.class) // 只在抛出空指针异常时重试
  • .retryIfException(Predicates.or(Predicates.instanceOf(NullPointerException.class),
    Predicates.instanceOf(IllegalStateException.class)))
  • retryIfResult 可以指定你的 Callable 方法在返回值的时候进行重试,如
  • .retryIfResult(Predicates.equalTo(false)) // 返回false重试
  • .retryIfResult(Predicates.containsPattern("_error$")) //以_error结尾才重试

2.3.2 自定义重试监听器 RetryListener

  • 当发生重试之后,假如我们需要做一些额外的处理动作,比如记录异常日志,那么可以使用RetryListener。
  • 每次重试之后,guava-retrying 会自动回调我们注册的监听。我们也可以注册多个RetryListener,会按照注册顺序依次调用。
.withRetryListener(new RetryListener {
	@Override
	public <T> void onRetry(Attempt<T> attempt) {
		logger.error("第【{}】次调用失败" , attempt.getAttemptNumber());
    }
}

2.3.3 停止重试策略 StopStrategy

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

2.3.4 等待时长策略(控制时间间隔)withWaitStrategy

  • FixedWait Strategy:固定等待时长策略。
  • RandomWait Strategy:随机等待时长策略(可以提供一个最小和最大时长,等待时长为其区间随机值)。
  • Incrementing WaitStrategy:递增等待时长策略(提供一个初始值和步长,等待时间随重试次数增加而增加)。
  • ExponentialWait Strategy:指数等待时长策略。
  • FibonacciWait Strategy :Fibonacci等待时长策略。
  • ExceptionWait Strategy:异常时长等待策略。
  • CompositeWait Strategy:复合时长等待策略。

3、guava-retrying demo

3.1 Maven依赖

引用Guava-Retrying的包

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

3.2 项目结构

java设置出错重试 java失败重试机制_java设置出错重试

  • RetryDemo.java
package com.xyy;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.google.common.base.Predicates;

import java.util.concurrent.TimeUnit;

import static com.github.rholder.retry.WaitStrategies.incrementingWait;

/**
 * @author wangxuexing
 * @descrption
 * @date
 */
public class RetryDemo {
    public static void main(String[] args) {
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder().
                //如果异常会重试
                retryIfException().
                //如果结果为false会重试
                retryIfResult(Predicates.equalTo(false)).
                //重调策略
                withWaitStrategy(incrementingWait(30, TimeUnit.SECONDS, 30, TimeUnit.SECONDS)).
                //尝试次数
                withStopStrategy(StopStrategies.stopAfterAttempt(3)).
                //注册监听
                withRetryListener(new MyRetryListener()).build();
        try {
            retryer.call(new TaskCallable());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • TaskCallable.java,其中TaskCallable是任务的具体实现类,它实现了Callable接口
package com.xyy;

import java.util.concurrent.Callable;


public class TaskCallable implements Callable<Boolean> {

    @Override
    public Boolean call() throws Exception {
        return false;
    }

}
  • MyRetryListener.java,MyRetryListener监听实现了RetryListener接口,每次重试都会回调注册的监听
package com.xyy;

import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryListener;

/**
 * @author wangxuexing
 * @descrption
 * @date
 */
public class MyRetryListener implements RetryListener {
    @Override
    public <V> void onRetry(Attempt<V> 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());
        }
        System.out.println();
    }
}
  • 执行结果