背景
最近在使用CompletableFuture做异步代码的重构,其中遇到了一些问题,记录下来。
需求
批量请求下游RPC的List,然后合并为一个List
代码
1.模拟调用下游请求
private CompletableFuture<List<Integer>> getIntegerList(int startIndex, int size) {
return CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Stream.iterate(startIndex, item -> item + 1).limit(size).collect(Collectors.toList());
}
);
}
2.使用CompletableFuture.thenCombine来聚合
@Test
public void testCompletableFutureWithCombine() {
List