基于guava的重试组件Guava-Retryer

在日常开发中,我们经常会遇到需要调用外部服务和接口的场景。外部服务对于调用者来说一般都是不可靠的,尤其是在网络环境比较差的情况下,网络抖动很容易导致请求超时等异常情况,这时候就需要使用失败重试策略重新调用 API 接口来获取。重试策略在服务治理方面也有很广泛的使用,通过定时检测,来查看服务是否存活。

Guava Retrying 是一个灵活方便的重试组件,包含了多种的重试策略,而且扩展起来非常容易。

使用 Guava-retrying 你可以自定义来执行重试,同时也可以监控每次重试的结果和行为,最重要的基于 Guava 风格的重试方式真的很方便。

代码示例

以下会简单列出 guava-retrying 的使用方式:

  • 如果抛出 IOException 则重试,如果返回结果为 null 或者等于 2 则重试,固定等待时长为 300 ms,最多尝试 3 次;

Callable task = new Callable() {

@Override

public Integer call() throws Exception {

return 2;

}

};

Retryer retryer = RetryerBuilder.newBuilder()

.retryIfResult(Predicates.isNull())

.retryIfResult(Predicates.equalTo(2))

.retryIfExceptionOfType(IOException.class)

.withStopStrategy(StopStrategies.stopAfterAttempt(3))

.withWaitStrategy(WaitStrategies.fixedWait(300, TimeUnit.MILLISECONDS))

.build();

try {

retryer.call(task);

} catch (ExecutionException e) {

e.printStackTrace();

} catch (RetryException e) {

e.printStackTrace();

}

依赖引入

com.github.rholder

guava-retrying

2.0.0


分享到:


相關文章: