1,添加依赖

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

2,重试机制的策略设置

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder().

retryIfException().

retryIfResult(Predicates.equalTo(false)).

withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)).

withStopStrategy(StopStrategies.stopAfterAttempt(3)).

withRetryListener(new MyRetryListener()).build();

(1)retryIfException:遇到异常重试
(2)retryIfException: 返回结果为false重试
(3)withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)):等待3秒重试一次
(4)withStopStrategy(StopStrategies.stopAfterAttempt(3)):重试三次
(5)withRetryListener(new MyRetryListener()).build():MyRetryListener为自定义的重试监听类,监听重试成功失败的信息
3,案例
(1)需要重试的业务类

import java.util.concurrent.Callable;

/**
* @author LiHaitao
* @description MyCallable:
* @date 2019/8/6 11:02
**/
public class MyCallable implements Callable {
private static int i = 0;

@Override
public Boolean call() throws Exception {
i++;
if (i <= 2) {
throw new Exception("重试次数达:" + i);
}
System.out.println("成功");
return true;
}
}

(2)监听类

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

/**
* @author LiHaitao
* @description MyRetryListener:
* @date 2019/8/6 11:00
**/
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());
}
}
}

(3)启动类

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

import java.util.concurrent.TimeUnit;

/**
* @author LiHaitao
* @description Main:
* @date 2019/8/6 11:02
**/
public class Main {

public static void main(String[] args) {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder().

retryIfException().

retryIfResult(Predicates.equalTo(false)).

withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)).

withStopStrategy(StopStrategies.stopAfterAttempt(3)).

withRetryListener(new MyRetryListener()).build();
try {
Boolean call = retryer.call(new MyCallable());//在此加入任务
} catch (Exception e) {
System.out.println(e.getMessage());

}

}
}