git地址:https://github.com/rholder/guava-retrying
maven依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
代码实现:
Retryer<Boolean> retryer = RetryerBuilder
.<Boolean>newBuilder()
.retryIfException().retryIfExceptionOfType(RuntimeException.class) //该异常抛出,retry
.retryIfResult(Predicates.equalTo(false)) //结果符合某些条件,retry
.withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS)) //retry的间隔
.withStopStrategy(StopStrategies.stopAfterAttempt(3)) //最大尝试此时
.withRetryListener(new JobRetryListener<>()) //监听器
.build();
try {
retryer.call(() -> {
System.out.println("retry");
return false;});
} catch (ExecutionException e) {
}
监听类
@Slf4j
public class JobRetryListener<Boolean> implements RetryListener {
@Override
public <V> void onRetry(Attempt<V> attempt) {
log.info("retry times: {}", attempt.getAttemptNumber());
log.info("delay time: {}", attempt.getDelaySinceFirstAttempt());
if (attempt.hasException()) {
log.info("causeBy: {}", attempt.getExceptionCause().toString());
} else {
// 正常返回时的结果
log.info(",result: {}", attempt.getResult());
}
}
}
参考:
https://www.jianshu.com/p/a289dde63043