CompletableFuture封装
CompletableTasks
在工作上经常会在接口中请求多个RPC请求,通过completableFuture 进行优化
public class CompletableTasks {
private List<CompletableFuture<?>> tasks;
public CompletableTasks() {
tasks = new ArrayList<>();
}
/**
* 填加任务
* @param supplier
* @return
* @param <T>
*/
public <T> CompletableTasks addTask(Supplier<T> supplier) {
return addTask(supplier, null);
}
/**
* 填加任务
* @param future
* @return
* @param <T>
*/
public <T> CompletableTasks addTask(CompletableFuture<T> future) {
tasks.add(future);
return this;
}
public <T> CompletableTasks addTask(Supplier<T> supplier, Executor executor) {
CompletableFuture<T> future;
if (executor != null) {
future = CompletableFuture.supplyAsync(supplier, executor);
} else {
future = CompletableFuture.supplyAsync(supplier);
}
tasks.add(future);
return this;
}
/**
* 阻塞调用
* @throws ExecutionException
* @throws InterruptedException
* @throws TimeoutException
*/
public void executeJoin() throws ExecutionException, InterruptedException, TimeoutException {
execute(null,null,null);
}
/**
*
* @param timeout
* @param timeUnit
* @param callBack 回调函数
* @throws ExecutionException
* @throws InterruptedException
* @throws TimeoutException
*/
public void execute(Long timeout, TimeUnit timeUnit, Consumer<List<Object>> callBack) throws ExecutionException,
InterruptedException,
TimeoutException {
CompletableFuture<?> future = CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0]))
.whenComplete((v, t) -> {
if (t!=null){
throw new BizException(BizCode.SEVER_ERROR.getCode(),BizCode.SEVER_ERROR.getMsg());
}
List<Object> result = new ArrayList<>();
for (CompletableFuture<?> task : tasks) {
result.add(task.getNow(null));
}
if (callBack!=null){
callBack.accept(result);
}
});
if (timeout == null) {
future.join();
} else {
future.get(timeout, timeUnit);
}
}
public static <T> T getObject(List<Object> result,int index,Class<T> clz){
if (CollectionUtils.isEmpty(result)){
return null;
}
if (index+1 > result.size()){
return null;
}
return (T) result.get(index);
}
public static <T> List<T> getObjectList(List<Object> result,int index,Class<T> clz){
if (CollectionUtils.isEmpty(result)){
return null;
}
if (index+1 > result.size()){
return null;
}
return (List<T>) result.get(index);
}
}
使用
CompletableTasks completableTasks = new CompletableTasks();
completableTasks.addTask(()->{
return "success";
}).execute(5L,TimeUnit.SECONDS, list ->{
//回调
String result = getObject(list, 0, String.class);
System.out.println(result);
});
结果:
success