TimeLimiter 组件
概述
TimeLimiter
用于限制真实调用的调用时间,它是一个函数式接口,定义如下:
java
public interface TimeLimiter<V> {
V callWithTimeout(Callable<V> callable, long duration, TimeUnit unit) throws TimeoutException,
InterruptedException, ExecutionException;
}
其中,duration
和unit
用于控制具体的调用时间(最大值限制)。Chance
提供多个TimeLimiter
的内置实现:
NoTimeLimiter
:对真实调用的不进行时间限制,这是默认启用的TimeLimiter
实现CompletableFutureTimeLimiter
:基于CompletableFuture
对真实调用进行包装进行时间限制,可以自定义Executor
ExecutorServiceTimeLimiter
:基于ExecutorService
对真实调用进行包装进行时间限制
使用 TimeLimiter
使用CompletableFutureTimeLimiter
:
java
// 使用全局共享的fork-join线程池
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withTimeLimiter(TimeLimiter.newCompletableFutureTimeLimiter(), 100, TimeUnit.MILLISECONDS)
.build();
// 自定义线程池
Executor executor = Executors.newSingleThreadExecutor();
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withTimeLimiter(TimeLimiter.newCompletableFutureTimeLimiter(executor), 100, TimeUnit.MILLISECONDS)
.build();
使用ExecutorServiceTimeLimiter
:
java
// 自定义线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withTimeLimiter(TimeLimiter.newExecutorServiceTimeLimiter(executorService), 100, TimeUnit.MILLISECONDS)
.build();
使用自定义TimeLimiter
:
java
class CustomTimeLimiter implements TimeLimiter<String> {
@Override
public String callWithTimeout(Callable callable, long duration, TimeUnit timeUnit)
throws TimeoutException, InterruptedException, ExecutionException {
// call callable with time limitation
return ...
}
}
// 使用CustomTimeLimiter
Chance<String> chance = Chance.<String, Throwable>newBuilder()
.withNeverRetry()
.withTimeLimiter(new CustomTimeLimiter(), 100, TimeUnit.MILLISECONDS)
.build();