Java 如何优雅的使用重试Retryer

好久没写过博客了,今天更新一下

给大家介绍一个重试的工具类

Guava-retrying

话不多说,直接上依赖

 

 



    com.github.rholder
    guava-retrying
    2.0.0

 

Retryer retryer = RetryerBuilder.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);
} catch (RetryException | ExecutionException e) {
    // 重试失败 后续操作
    // ...
    e.printStackTrace();
}

 

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比循环优雅的多了吧

需要的拿走不谢

你可能感兴趣的:(笔记)