提问者:小点点

Java 8中使用CompletableFuture的异步api调用


以下是我尝试使用“可完成未来”类实现的用例

  1. 我有一个id列表,我想为每个id调用api
  2. 我想从api调用中获得响应,并将其保存在列表或映射中,以便进一步处理
  3. 我也不想等到得到所有api调用的响应。我想设定一个时间限制,并在那之前获取所有可用的数据

我尝试了以下代码,但它不能正常工作

// list content
List<Integer> ids = Arrays.asList(1,2,3,4,5);


// Api call using parallel stream - not sure how I can include a time limit here so that
// I can get partial list of updatedIds based on delay settings
List<Integer> updatedIds  = ids.parallelStream().map(item -> {
            // api call equivalent of increment 1
            return item+1;
        }).collect(Collectors.toList());



// Asynchronous api call using CompletableFuture class - not sure how I can
// dynamically call the function for all items in the ids list.
// Following is what I tried to do by reading 
// https://www.baeldung.com/java-completablefuture
encounterIdSet.parallelStream().forEach(id -> {
     CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> serviceCall(id));
});
List<Integer> = completableFuture.get(60, TimeUnit.SECONDS); // may be in incorrect location 



// I want to process the list of returned integers here - whatever I am getting in 60 seconds timeout mentioned in timeout settings



// service call definition 
Integer serviceCall(id){
  return id +1;
}

您能指导我这个用例吗?我需要 1.超时设置为 2。异步数据处理 3.未知的项目数。

我正在使用Java 8。

谢谢。


共1个答案

匿名用户

我可以想到两种方式,但有一些细微的区别:

    List<CompletableFuture<Integer>> futures = ids.stream()
            .map(id -> CompletableFuture.supplyAsync(() -> id + 1))
            .collect(Collectors.toList());
    try {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(60, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        // log
    }
    List<Integer> result = futures
            .stream()
            .filter(future -> future.isDone() && !future.isCompletedExceptionally())
            .map(CompletableFuture::join)
            .collect(Collectors.toList());   

或者

     List<Integer> result = ids.stream()
            .map(id -> CompletableFuture.supplyAsync(() -> id + 1))
            .map(cf -> {
                    try {
                        return cf.get(60, TimeUnit.SECONDS);
                    } catch (InterruptedException | ExecutionException | TimeoutException e) {
                        // log
                    }
                    return null;
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());