文章目录

Guava-retrying

1. 主要相关类

1.1 Attemp 类


1.2 Retryer 类

call 方法源码如下:

	public V call(Callable<V> callable) throws ExecutionException, RetryException {
        long startTime = System.nanoTime();
        for (int attemptNumber = 1; ; attemptNumber++) {
            Attempt<V> attempt;
            try {
                // 任务执行的时间限制
                V result = attemptTimeLimiter.call(callable);
                attempt = new ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
            } catch (Throwable t) {
                attempt = new ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
            }

            for (RetryListener listener : listeners) {
                listener.onRetry(attempt);
            }
            // 判断是否满足重试条件,来决定是否继续等待并进行重试
            if (!rejectionPredicate.apply(attempt)) {
                return attempt.get();
            }
            //重试停止 策略
            if (stopStrategy.shouldStop(attempt)) {
                throw new RetryException(attemptNumber, attempt);
            } else {
                // 重试等待 策略
                long sleepTime = waitStrategy.computeSleepTime(attempt);
                try {
                    // 根据重试等待计算的时间,执行阻塞策略
                    blockStrategy.block(sleepTime);
                } catch (InterruptedException e) {
                    // 线程中断,抛出异常
                    Thread.currentThread().interrupt();
                    throw new RetryException(attemptNumber, attempt);
                }
            }
        }
    }

1.3 RetryListener

	@Beta
	public interface RetryListener {
		// 监听方法
	    <V> void onRetry(Attempt<V> var1);
	}



2. WaitStrategies 重试等待策略

2.1 ExponentialWaitStrategy 指数等待策略(WaitStrategies.exponentialWait)


2.2 FibonacciWaitStrategy 斐波那契等待策略(WaitStrategies.fibonacciWait)


2.3 FixedWaitStrategy 固定时长等待策略(WaitStrategies.fixedWait)


2.4 RandomWaitStrategy 随机时长等待策略(WaitStrategies.randomWait)


2.5 IncrementingWaitStrategy 递增等待策略(WaitStrategies.incrementingWait)


2.6 ExceptionWaitStrategy 异常等待策略(WaitStrategies.exceptionWait)


2.7 CompositeWaitStrategy 复合等待策略 【***】(WaitStrategies.join)




3. StopStrategies 重试停止策略

3.1 NeverStopStrategy 无限制重试(StopStrategies.neverStop)

3.2 StopAfterAttemptStrategy 重试指定次数停止(StopStrategies.stopAfterAttempt)

3.3 StopAfterDelayStrategy 重试指定时长后结束(StopStrategies.stopAfterDelay)




4 AttemptTimeLimiters 任务执行时长限制(withAttemptTimeLimiter)

4.1 FixedAttemptTimeLimit 指定执行时长限制(AttemptTimeLimiters.fixedTimeLimit)

4.2 NoAttemptTimeLimit 无时长限制(AttemptTimeLimiters.noTimeLimit)




5. BlockStrategies 阻塞策略

6. 封装使用

12-08 07:41