使用場景
在日常開發中,我們經常會遇到需要調用外部服務和接口的場景。外部服務對於調用者來說一般都是不可靠的,尤其是在網絡環境比較差的情況下,網絡抖動很容易導致請求超時等異常情況,這時候就需要使用失敗重試策略重新調用 API 接口來獲取。重試策略在服務治理方面也有很廣泛的使用,通過定時檢測,來查看服務是否存活。
Guava Retrying 是一個靈活方便的重試組件,包含了多種的重試策略,而且擴展起來非常容易。
用作者的話來說:
This is a small extension to Google’s Guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flaky uptime.
使用 Guava-retrying 你可以自定義來執行重試,同時也可以監控每次重試的結果和行為,最重要的基於 Guava 風格的重試方式真的很方便。
網上關於guava-retrying的介紹很多,我就不贅述了,這里有一篇寫的比較好的文章:
在此基礎上我封裝了一個Util:
/**
* Created by libing6@xiaomi.com on 18-7-12.
*/
@Log4j2
public class RetryUtil {
//出現異常則執行重試,每次任務執行最長執行時間限定為 3 s,重試間隔時間初始為 3 s,最多重試 10秒,隨着重試次數的增加每次遞增 1 s,每次重試失敗,打印日志;
public static <T> Retryer<T> getADefaultRetryer() {
Retryer<T> retryer = RetryerBuilder.<T>newBuilder()
.retryIfException()
.withStopStrategy(
StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))
.withWaitStrategy(
WaitStrategies.incrementingWait(3, TimeUnit.SECONDS, 1, TimeUnit.SECONDS))
.withAttemptTimeLimiter(
AttemptTimeLimiters.fixedTimeLimit(3, TimeUnit.SECONDS))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
log.debug("retry time = " + attempt.getAttemptNumber());
if (attempt.hasException()) {
log.error("try failed", attempt.getExceptionCause());
}
}
})
.build();
return retryer;
}
// Todo 可以定制參數
}
使用方法僅需一句話:
RetryUtil.<String>getADefaultRetryer()
.call(() -> getClient().getDataById(id));