给大家介绍一个重试的工具类
Guava-retrying
<!-- https://mvnrepository.com/artifact/com.github.rholder/guava-retrying -->
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
//抛出runtime异常、checked异常时都会重试,但是抛出error不会重试。
.retryIfException()
//返回false也需要重试(可以根据返回值确定需不需要重试)
.retryIfResult(Predicates.equalTo(false))
//重调策略
.withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS))
//尝试次数
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
retryer.call(callable);
// 例如:retryer.call(() -> iceClient.getId(product, appId));
} catch (RetryException | ExecutionException e) {
// 重试失败 后续操作
// ...
e.printStackTrace();
}
callable主体方法,返回boolean,true则终止retry
RetryerBuilder
RetryerBuilder 是一个 factory 创建者,可以定制设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔,创建重试者 Retryer 实例。
RetryerBuilder 的重试源支持 Exception 异常对象和自定义断言对象,通过retryIfException 和 retryIfResult 设置,同时支持多个且能兼容。
retryIfException
retryIfException,抛出 runtime 异常、checked 异常时都会重试,但是抛出 error 不会重试。
retryIfRuntimeException
retryIfRuntimeException 只会在抛 runtime 异常的时候才重试,checked 异常和error 都不重试。
retryIfExceptionOfType
retryIfExceptionOfType 允许我们只在发生特定异常的时候才重试,比如NullPointerException 和 IllegalStateException 都属于 runtime 异常,也包括自定义的error。
这样写出来的Retry比循环优雅的多了吧
————————————————
版权声明:本文为CSDN博主「HarryGuoBa」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u014534986/article/details/102862333