guava-retrying

guava-retrying

guava-retrying 模块提供了一种通用方法, 可以使用Guava谓词匹配增强的特定停止、重试和异常处理功能来重试任意Java代码。

  • 优势

guava retryer工具与spring-retry类似,都是通过定义重试者角色来包装正常逻辑重试,但是Guava retryer有更优的策略定义,在支持重试次数和重试频度控制基础上,能够兼容支持多个异常或者自定义实体对象的重试源定义,让重试功能有更多的灵活性。

Guava Retryer也是线程安全的,入口调用逻辑采用的是 java.util.concurrent.Callable 的 call() 方法

代码例子

 

引入依赖

 

<dependency>
    <groupId>com.github.rholder</groupId>
    <artifactId>guava-retrying</artifactId>
    <version>2.0.0</version>
</dependency>

入门案例

遇到异常之后,重试 3 次停止

  • HelloDemo.java

public static void main(String[] args) { Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() throws Exception { // do something useful here LOGGER.info("call..."); throw new RuntimeException(); } }; Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.isNull()) .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); } catch (RetryException | ExecutionException e) { e.printStackTrace(); } }

  • 日志

2018-08-08 17:21:12.442 INFO [main] com.github.houbb.retry.guava.HelloDemo:41 - call... com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts. 2018-08-08 17:21:12.443 INFO [main] com.github.houbb.retry.guava.HelloDemo:41 - call... 2018-08-08 17:21:12.444 INFO [main] com.github.houbb.retry.guava.HelloDemo:41 - call... at com.github.rholder.retry.Retryer.call(Retryer.java:174) at com.github.houbb.retry.guava.HelloDemo.main(HelloDemo.java:53) Caused by: java.lang.RuntimeException at com.github.houbb.retry.guava.HelloDemo$1.call(HelloDemo.java:42) at com.github.houbb.retry.guava.HelloDemo$1.call(HelloDemo.java:37) at com.github.rholder.retry.AttemptTimeLimiters$NoAttemptTimeLimit.call(AttemptTimeLimiters.java:78) at com.github.rholder.retry.Retryer.call(Retryer.java:160) ... 1 more

重试策略

  • ExponentialBackoff.java

重试次数:3

重试策略:固定等待 3S

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.isNull()) .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); } catch (RetryException | ExecutionException e) { e.printStackTrace(); }

  • 日志

2018-08-08 17:20:41.653 INFO [main] com.github.houbb.retry.guava.ExponentialBackoff:43 - call... 2018-08-08 17:20:44.659 INFO [main] com.github.houbb.retry.guava.ExponentialBackoff:43 - call... 2018-08-08 17:20:47.664 INFO [main] com.github.houbb.retry.guava.ExponentialBackoff:43 - call... com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts. at com.github.rholder.retry.Retryer.call(Retryer.java:174) at com.github.houbb.retry.guava.ExponentialBackoff.main(ExponentialBackoff.java:56) Caused by: java.lang.RuntimeException at com.github.houbb.retry.guava.ExponentialBackoff$1.call(ExponentialBackoff.java:44) at com.github.houbb.retry.guava.ExponentialBackoff$1.call(ExponentialBackoff.java:39) at com.github.rholder.retry.AttemptTimeLimiters$NoAttemptTimeLimit.call(AttemptTimeLimiters.java:78) at com.github.rholder.retry.Retryer.call(Retryer.java:160) ... 1 more

guava-retrying 简介

RetryerBuilder

RetryerBuilder 是一个 factory 创建者,可以定制设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔,创建重试者 Retryer 实例。

RetryerBuilder 的重试源支持 Exception 异常对象和自定义断言对象,通过retryIfException 和 retryIfResult 设置,同时支持多个且能兼容。

  • retryIfException

retryIfException,抛出 runtime 异常、checked 异常时都会重试,但是抛出 error 不会重试。

  • retryIfRuntimeException

retryIfRuntimeException 只会在抛 runtime 异常的时候才重试,checked 异常和error 都不重试。

  • retryIfExceptionOfType

retryIfExceptionOfType 允许我们只在发生特定异常的时候才重试,比如NullPointerException 和 IllegalStateException 都属于 runtime 异常,也包括自定义的error。

如:  

retryIfExceptionOfType(Error.class)// 只在抛出error重试

当然我们还可以在只有出现指定的异常的时候才重试,如: 

```java 

.retryIfExceptionOfType(IllegalStateException.class)

.retryIfExceptionOfType(NullPointerException.class)

或者通过Predicate实现 ```java .retryIfException(Predicates.or(Predicates.instanceOf(NullPointerException.class), Predicates.instanceOf(IllegalStateException.class)))

  • retryIfResult

retryIfResult 可以指定你的 Callable 方法在返回值的时候进行重试,如  

// 返回false重试 .retryIfResult(Predicates.equalTo(false)) //以_error结尾才重试 .retryIfResult(Predicates.containsPattern("_error$"))

  • RetryListener

当发生重试之后,假如我们需要做一些额外的处理动作,比如log一下异常,那么可以使用RetryListener。

每次重试之后,guava-retrying 会自动回调我们注册的监听。

可以注册多个RetryListener,会按照注册顺序依次调用。  

.withRetryListener(new RetryListener { @Override public <T> void onRetry(Attempt<T> attempt) { logger.error("第【{}】次调用失败" , attempt.getAttemptNumber()); } } )

主要接口

序号

接口

描述

备注

  

1

Attempt

一次执行任务

   

2

AttemptTimeLimiter

单次任务执行时间限制

如果单次任务执行超时,则终止执行当前任务

  

3

BlockStrategies

任务阻塞策略

通俗的讲就是当前任务执行完,下次任务还没开始这段时间做什么),默认策略为:BlockStrategies.THREAD_SLEEP_STRATEGY

  

4

RetryException

重试异常

   

5

RetryListener

自定义重试监听器

可以用于异步记录错误日志

  

6

StopStrategy

停止重试策略

   

7

WaitStrategy

等待时长策略

(控制时间间隔),返回结果为下次执行时长

  

8

Attempt

一次执行任务

   

9

Attempt

一次执行任务

   

StopStrategy

提供三种:

  • StopAfterDelayStrategy

设定一个最长允许的执行时间;比如设定最长执行10s,无论任务执行次数,只要重试的时候超出了最长时间,则任务终止,并返回重试异常RetryException;

  • NeverStopStrategy

不停止,用于需要一直轮训知道返回期望结果的情况;

  • StopAfterAttemptStrategy

设定最大重试次数,如果超出最大重试次数则停止重试,并返回重试异常;

WaitStrategy

  • FixedWaitStrategy

固定等待时长策略;

  • RandomWaitStrategy

随机等待时长策略(可以提供一个最小和最大时长,等待时长为其区间随机值)

  • IncrementingWaitStrategy

递增等待时长策略(提供一个初始值和步长,等待时间随重试次数增加而增加)

  • ExponentialWaitStrategy

指数等待时长策略;

  • FibonacciWaitStrategy

Fibonacci 等待时长策略;

  • ExceptionWaitStrategy

异常时长等待策略;

  • CompositeWaitStrategy

复合时长等待策略;

转载于:https://my.oschina.net/iioschina/blog/2967611

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值