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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-12 01:31:42 +0000
Seen: 15 times
Last updated: Jun 12 '23
Why am I not getting a response when making a URL call in ASP.NET Web API?
How can the Discord Ping Command be implemented with the Websocket API?
What is the process for converting a cURL request to VBA WinHttp.WinHttpRequest.5.1?
What is the process for validating an FCM registration token on a server?
Can the response be worded as: 'Error 404 - city not found'?
What is the method for creating a Plotly graph in ReactJS using a JSON response?