To unblock HTTP calls on Spring RestTemplates when using CompletableFuture, you can use the following approach:
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactoryClientHttpRequestFactory());
HttpComponentsClientHttpRequestFactory requestFactory = (HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory();
requestFactory.setConnectTimeout(100);
requestFactory.setReadTimeout(100);
Use CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url, SomeResponse.class)) to perform the HTTP call asynchronously.
Use the thenApply() method to handle the response asynchronously.
CompletableFuture<SomeResponse> futureResponse = CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url, SomeResponse.class));
CompletableFuture<Void> futureHandling = futureResponse.thenApply((result) -> {
SomeResponse response = result;
// Process the response here
return null;
});
By creating a RestTemplate instance with a low timeout value, you avoid blocking the thread for too long while the HTTP call is performed. By using CompletableFuture to perform the HTTP call asynchronously, you don't block the calling thread while waiting for the response. Finally, using thenApply() to handle the response asynchronously ensures that the response processing doesn't block the calling thread either.
Asked: 2023-06-12 01:31:42 +0000
Seen: 15 times
Last updated: Jun 12 '23