我在项目中设置了RestTemplate和AsyncRestTemplate,如下所示:
http://vincentdevillers.blogspot.fr/2013/10/a-best-spring-asyncresttemplate.html
我注意到,除非将httpRequestFactory()bean更改为以下内容,否则连接超时实际上不会起作用:
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
factory.setConnectTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
factory.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
return factory;
}
如果我将DEFAULT_READ_TIMEOUT_MILLISECONDS设置为5,则当我使用restTemplate时(如预期的那样)会发生超时。但是,当我使用AsyncRestTemplate时,不会发生超时。我已经像httpRequestFactory()一样修改了asyncHttpRequestFactory(),但是没有骰子。
@Bean
public AsyncClientHttpRequestFactory asyncHttpRequestFactory() {
HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory(asyncHttpClient());
factory.setConnectTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
factory.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
return factory;
}
这是我尝试在Spring MVC Controller中使用AsyncRestTemplate的方法:
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();
如何获取AsyncRestTemplate来读取我的连接超时设置?
在相关说明中,https://spring.io/guides/gs/async-method/使用@Async和RestTemplate并似乎完成了我想要的。与RestTemplate相比,使用AsyncRestTemplate有什么优势?
最佳答案
与sync非常相似:
final SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setTaskExecutor(new SimpleAsyncTaskExecutor());
requestFactory.setConnectTimeout(connectTimeout);
requestFactory.setReadTimeout(readTimeout);
final AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
asyncRestTemplate.setAsyncRequestFactory(requestFactory);
从source code中,您可以看到
AsyncRestTemplate
实例是通过将SimpleClientHttpRequestFactory
和SimpleAsyncTaskExecutor
一起使用创建的。因此,您可以使用设置了超时值的SimpleClientHttpRequestFactory
实例执行相同的操作。