public class ScopeAsyncRetry extends Object
Scope 级联,并且支持单次调用独立设置超时的异步重试封装
使用方法:
class MyClass {
private final ScopeAsyncRetry retrier = ScopeAsyncRetry.shared();
private final ListeningExecutorService executor = listeningDecorator(newFixedThreadPool(10);
ListenableFuture<String> asyncCall() {
return executor.submit(() -> {
sleepUninterruptibly(ThreadLocalRandom.current().nextLong(150L), MILLISECONDS);
return "myTest"
});
}
void foo() throws ExecutionException, TimeoutException {
ListenableFuture<String> future = retrier.callWithRetry(100, retryNTimes(3), () -> asyncCall());
String unwrapped = getUninterruptibly(future, 200, MILLISECONDS);
System.out.println("result is:" + unwrapped);
}
}
注意: 如果最终外部的ListenableFuture.get(timeout)没有超时,但是内部请求都失败了,则上抛
会上抛 ExecutionException 并包含最后一次重试的结果
特别的,如果最后一次请求超时 Throwable.getCause() 为 TimeoutException
注意: 需要重试的方法应该是幂等的操作,不应有任何副作用。
| Modifier and Type | Method and Description |
|---|---|
<T,X extends Throwable> |
callWithRetry(long singleCallTimeoutMs,
RetryPolicy retryPolicy,
com.github.phantomthief.util.ThrowableSupplier<com.google.common.util.concurrent.ListenableFuture<T>,X> func)
带重试的调用
|
<T,X extends Throwable> |
callWithRetry(long singleCallTimeoutMs,
RetryPolicy retryPolicy,
com.github.phantomthief.util.ThrowableSupplier<com.google.common.util.concurrent.ListenableFuture<T>,X> func,
com.google.common.util.concurrent.FutureCallback<T> eachRetryCallback) |
static ScopeAsyncRetry |
createScopeAsyncRetry(ScheduledExecutorService executor)
Deprecated.
|
static ScopeAsyncRetry |
createScopeAsyncRetry(ScheduledExecutorService executor,
Executor callbackExecutor) |
static ScopeAsyncRetry |
shared()
共享的 ScopeAsyncRetry 实例
|
@Deprecated public static ScopeAsyncRetry createScopeAsyncRetry(@Nonnegative ScheduledExecutorService executor)
createScopeAsyncRetry(ScheduledExecutorService, Executor)public static ScopeAsyncRetry createScopeAsyncRetry(@Nonnegative ScheduledExecutorService executor, Executor callbackExecutor)
public static ScopeAsyncRetry shared()
建议不同业务使用不同的实例,因为其中通过 ScheduledExecutorService 来检测超时 和 实现间隔重试 大量使用共享实例,这里可能成为瓶颈
@Nonnull public <T,X extends Throwable> com.google.common.util.concurrent.ListenableFuture<T> callWithRetry(long singleCallTimeoutMs, RetryPolicy retryPolicy, @Nonnull com.github.phantomthief.util.ThrowableSupplier<com.google.common.util.concurrent.ListenableFuture<T>,X> func)
singleCallTimeoutMs - 单次调用超时限制,单位:msfunc - 需要重试的调用@Nonnull public <T,X extends Throwable> com.google.common.util.concurrent.ListenableFuture<T> callWithRetry(long singleCallTimeoutMs, RetryPolicy retryPolicy, @Nonnull com.github.phantomthief.util.ThrowableSupplier<com.google.common.util.concurrent.ListenableFuture<T>,X> func, @Nullable com.google.common.util.concurrent.FutureCallback<T> eachRetryCallback)
Copyright © 2019. All rights reserved.