我正在开发一个项目,在该项目中,我需要对运行Restful Service
的服务器进行HTTP URL调用,该服务器将响应作为JSON字符串返回。如何在多线程环境中有效使用RestTemplate?
下面是一个使用future
和callables
我的主要代码 -
public class TimeoutThreadExample {
private ExecutorService executor = Executors.newFixedThreadPool(10);
public String getData() {
Future<String> future = executor.submit(new Task());
String response = null;
try {
response = future.get(100, 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 = new RestTemplate();
public String call() throws Exception {
String url = "some_url";
String response = restTemplate.getForObject(url, String.class);
return response;
}
}
现在我在类5000 times
sequery中调用getData
方法的另一个类DemoTest
中的代码如下entially -
public class DemoTest {
public static void main(String[] args) {
TimeoutThreadExample bc = new TimeoutThreadExample();
for (int i = 0; i <= 5000; i++) {
// TimerTest timer = TimerTest.getInstance(); // line 1
bc.getData();
// timer.getDuration(); // line 2
}
}
}
所以我的问题是应该RestTemplate
在这里是静态的我Task class
,如果我正确地看到它,我重新创建在RestTemplate
每个请求这不是我想以正确的方式在整个连接池..
注:如果我提出RestTemplate静态的,那么,我认为作为DemoTest
类措施成效注释掉一号线2号线和后相比,非静态RestTemplate
更好的性能端到端。
一般来说,在多线程环境中使用RestTemplate
的正确方法是什么?目前我按顺序依次调用getData
方法5000次,但有些客户会以多线程方式调用它,所以需要知道在多线程环境中使用RestTemplate的最佳方式是什么。
可能是在ConnectionFactory中使用RestTemplate的构造函数?有什么想法吗?
更新: -
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(100, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return response;
}
}
而且下面我TaskClass
-
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;
}
}
可能的重复[如何提高性能,同时使用ExecutorService线程超时功能?](http://stackoverflow.com/questions/21241036/how-to-improve-the-performance-while-using-executorservice- with-thread-timeout-c) –