网络异常在我们日常开发中经常会遇到,这种情况下我们需要先重试几次调用才能将其标识为错误并在确认错误之后发送异常提醒。guava-retry可以灵活的实现这一功能
引入Guava-retry
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
只需要将实现Callable接口的方法传入,以便Guava retryer能够调用就可以了
private <T extends List> T executeWithRetry(Callable<T> callable) throws ExecutionException, RetryException {
return RetryerBuilder.<T>newBuilder()
.retryIfExceptionOfType(TException.class)
//遇到TException
.retryIfRuntimeException()
//遇到RuntimeException
.retryIfResult(CollectionUtils::isEmpty)
//查询出的数据为空
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
//间隔一秒调一次
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
//总共调三次
.build().call(callable);
}