当前位置: 欣欣网 > 码农

今日代码大赏 | Guava 重试

2024-04-01码农

在后端开发中,我们经常需要对接第三方的接口,

为了防止由于第三方接口不稳定或网络抖动导致的异常,我们通常会给这类接口加一个重试的机制,

Guava 中为我们提供了现成的重试方法,

示例代码如下:

Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
// callable返回null时重试
.retryIfResult(Predicates.isNull())
// callable抛出Exception重试
.retryIfException()
// 等待策略
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
// 重试 3 次后停止
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
retryer.call(() -> {
if (RandomUtil.randomInt(01) < 0.5) {
thrownewRuntimeException();
}
return"代码小抄";
});

整代码片段来源于代码小抄,欢迎点击进入小程序阅读!

在线访问:https://www.codecopy.cn/post/6el9ux

更多优质代码欢迎进入小程序查看!

往期推荐