I installed RestTemplate and AsyncRestTemplate in my project similar to the following:
http://vincentdevillers.blogspot.fr/2013/10/a-best-spring-asyncresttemplate.html
I noticed that the connection timeout did not actually work unless I changed the httpRequestFactory () bean as follows:
@Bean public ClientHttpRequestFactory httpRequestFactory() { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient()); factory.setConnectTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); factory.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); return factory; }
If I set DEFAULT_READ_TIMEOUT_MILLISECONDS to 5, a timeout will occur when I use restTemplate (as expected). However, when I use AsyncRestTemplate, a timeout does not occur. I changed asyncHttpRequestFactory () as httpRequestFactory (), but not a cube.
@Bean public AsyncClientHttpRequestFactory asyncHttpRequestFactory() { HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(asyncHttpClient()); factory.setConnectTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); factory.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS); return factory; }
This is how I try to use AsyncRestTemplate in a Spring MVC controller:
String url = "..."; // Start the clock long start = System.currentTimeMillis(); ListenableFuture<ResponseEntity<String>> results = asyncRestTemplate.getForEntity(url, String.class); // Wait until the request is finished while (!(results.isDone())) { Thread.sleep(10); //millisecond pause between each check } System.out.println("Elapsed time: " + (System.currentTimeMillis() - start)); return results.get().getBody();
How can I get an AsyncRestTemplate to read connection timeout settings?
In a related note, https://spring.io/guides/gs/async-method/ uses @Async and RestTemplate and seems to do what I'm looking for. What is the advantage of using AsyncRestTemplate over RestTemplate?
spring asynchronous spring-mvc resttemplate
Matt raible
source share