我正在開發一個項目,在該項目中,我需要對運行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) –