pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
<!-- 排除与guava重复的依赖 -->
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
</exclusion>
</exclusions>
</dependency>
code
public static void main(String[] args) {
String msg = "aaabbb";
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("length:".concat(msg.length() + ""));
return msg.length();
}
};
//返回异常或返回6或返回null,都会触发重试机制。最多执行4次(首次 + 重试3次),每次延迟5s。
Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
.retryIfResult(Predicates.<Integer>isNull())
.retryIfResult(Predicates.equalTo(6))
.retryIfExceptionOfType(Exception.class)
.withStopStrategy(StopStrategies.stopAfterAttempt(4))
.withWaitStrategy(WaitStrategies.fixedWait(5*1000, TimeUnit.MILLISECONDS))
.build();
try {
retryer.call(task);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (RetryException e) {
log.error("重试3次依旧未能获得期望值");
// e.printStackTrace();
}
}