Guava Retryer轻松实现接口重试( 二 )


@Slf4jclass diyRetryListener<Boolean> implements RetryListener {@Overridepublic <Boolean> void onRetry(Attempt<Boolean> attempt) {log.info("重试次数:{}",attempt.getAttemptNumber());log.info("距离第一次重试的延迟:{}",attempt.getDelaySinceFirstAttempt());if(attempt.hasException()){log.error("异常原因:",attempt.getExceptionCause());}else {System.out.println("正常处理结果:{}" + attempt.getResult());}}}定义监听器之后,需要在Retryer中进行注册 。
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder().retryIfResult(Predicates.<Boolean>isNull()) // callable返回null时重试.retryIfExceptionOfType(IOException.class) // callable抛出IOException重试.retryIfRuntimeException() // callable抛出RuntimeException重试.withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 重试3次后停止.withRetryListener(new DiyRetryListener<Boolean>()) // 注册监听器.build();小结Guava Retryer不光在重试策略上支持多种选择,并且将业务逻辑的处理放在Callable中,和重试处理逻辑分开,实现了解耦,这比小黑自己去写循环处理要优秀太多啦,Guava确实强大 。




推荐阅读