[英]Asynchronous api call using CompletableFuture in Java 8
以下是我嘗試使用 CompletableFuture 類實現的用例
我嘗試了以下代碼,但無法正常工作
// 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。
謝謝。
我可以想到兩種方法,但有一些細微差別:
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.