【发布时间】:2014-10-31 03:02:55
【问题描述】:
我正在处理一个项目,在该项目中我需要对运行 Restful 服务的服务器进行 HTTP URL 调用,该服务以JSON String 的形式返回响应。
下面是我使用future和callables的主要代码:
public class TimeoutThreadExample {
private ExecutorService executor = Executors.newFixedThreadPool(10);
private RestTemplate restTemplate = new RestTemplate();
public String getData() {
Future<String> future = executor.submit(new Task(restTemplate));
String response = null;
try {
response = future.get(500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return response;
}
}
下面是我的Task 类,它实现了Callable 接口并使用RestTemplate:
class Task implements Callable<String> {
private RestTemplate restTemplate;
public Task(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String call() throws Exception {
String url = "some_url";
String response = restTemplate.getForObject(url, String.class);
return response;
}
}
问题陈述:
正如您在上面看到的,我使用默认方式使用RestTemplate 执行 URL,它不使用任何 Http 请求超时,这意味着它在内部使用 -1 作为 read 和 connection暂停。
现在我想做的是,我想在上面的代码中使用RestTemplate 有效地设置 Http 请求超时。而且我不确定我需要使用哪个类,我可以看到 HttpComponentsClientHttpRequestFactory 和 SimpleClientHttpRequestFactory 所以不确定我需要使用哪个类?
任何基于我上面代码的简单示例将帮助我更好地理解如何使用RestTemplate 设置 Http 请求超时。
而且我的 Http 请求超时值是否应该小于未来的超时值?
-
HttpComponentsClientHttpRequestFactory与SimpleClientHttpRequestFactory。使用哪一个? - 我的 Http 请求超时值是否应该小于将来的超时值?
【问题讨论】:
标签: java multithreading spring httprequest resttemplate