Ask Your Question
0

How can I unblock HTTP calls on Spring RestTemplates when using CompletableFuture?

asked 2023-06-12 01:31:42 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-12 01:44:01 +0000

devzero gravatar image

To unblock HTTP calls on Spring RestTemplates when using CompletableFuture, you can use the following approach:

  1. Create a RestTemplate instance with an HttpComponentsClientHttpRequestFactory that sets the connection timeout and the socket timeout to a low value, such as 100 milliseconds.
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactoryClientHttpRequestFactory());
HttpComponentsClientHttpRequestFactory requestFactory = (HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory();
requestFactory.setConnectTimeout(100);
requestFactory.setReadTimeout(100);
  1. Use CompletableFuture.supplyAsync(() -> restTemplate.getForObject(url, SomeResponse.class)) to perform the HTTP call asynchronously.

  2. 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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-12 01:31:42 +0000

Seen: 15 times

Last updated: Jun 12 '23