一、前言
好的代码应该具备健壮性,比如代码里面调用了一个http请求,如果当时网络抖了下,http就调用失败了,这时候我们往往需要重试,本文我们就来介绍一个功能比较完善的重试组件-Retryer。
二、Retryer介绍
使用组件需要首先在项目中引入maven依赖:
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
下面我们通过一个例子,来看如何使用该组件:
// 1.创建重试器对象
private final static Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Predicates.<Boolean>isNull())// 1.1当重试的方法返回null时候进行重试
.retryIfExceptionOfType(IOException.class)// 1.2当重试方法抛出IOException类型异常时候进行重试
.withStopStrategy(StopStrategies.stopAfterAttempt(3))// 1.3尝试执行三次(也就是重试2次)
.withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))//1.4重试间隔
.build();
public static void main(String[] args) {
// 2需要重试的方法
Callable<Boolean> callable = new Callable<Boolean>(