當前位置: 妍妍網 > 碼農

今日程式碼大賞 | 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

更多優質程式碼歡迎進入小程式檢視!

往期推薦