I’m making multiple API calls at the same time with CompletableFuture to reduce user waiting time.
Here is my code:
@Async
public CompletableFuture<CommonDataDTO> commonData() throws JsonProcessingException, ExecutionException, InterruptedException {
CompletableFuture<UserDTO[]> completableFutureUser = CompletableFuture.supplyAsync(() -> {
try {
return apiHelper.getEmployee();
} catch (JsonProcessingException e) {
return new UserDTO[0];
}
});
CompletableFuture<ContactDTO[]> completableFutureContact = CompletableFuture.supplyAsync(() -> {
try {
return apiHelper.getTravelAgent();
} catch (JsonProcessingException e) {
return new ContactDTO[0];
}
});
CompletableFuture<CurrencyRateDTO[]> completableFutureCurrency = CompletableFuture.supplyAsync(() -> apiHelper.getCurrencyRate("site"));
return CompletableFuture.allOf(completableFutureUser, completableFutureContact, completableFutureCurrency).thenApply(v -> {
return new CommonDataDTO(Arrays.stream(completableFutureUser.join()).toList(), Arrays.stream(completableFutureContact.join()).toList(), Arrays.stream(completableFutureCurrency.join()).toList());
});
}
But when I run the above code I get an error message like:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
I added @EnableAsync
to the Application class.
Am I doing something wrong here?
Many thanks
I tried replacing allOf with thenCompine but everything is still the same