I wanna asynchronously call an external api for 3 times and wait them return. My code likes below:
public ResponseClass callApi(xxx) {
// ... other code
ResponseClass response = restTemplate.postForEntity(
requestUrl,
httpEntity,
ResponseClass.class
).getBody();
return response;
}
public void otherMethod() {
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
callApi(xxx);
});
CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
callApi(xxx);
});
CompletableFuture<Void> completableFuture3 = CompletableFuture.runAsync(() -> {
callApi(xxx);
});
CompletableFuture.allOf(completableFuture).join();
}
I expect process will wait for all 3 call return after CompletableFuture.allOf
, But what I got is an exception:
java.util.concurrent.CompletionException: org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class ...
I was so confused since it works fine when I call them synchronously ( without CompletableFuture ).
So, could someone help me find a way to do that? Thanks very much.
Create a list of CompletableFuture and add try to add your 3 CompletableFuture like below.
List<CompletableFuture<Void>> completableFutures = new ArrayList<>(10);
completableFutures.add(completableFuture1);
completableFutures.add(completableFuture2);
completableFutures.add(completableFuture3);
and then finally use CompletableFuture.allOf
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.