I am working on a project in which I need to make an HTTP URL call to my server, running RESTful service, which returns the response as a JSON
String. I am using RestTemplate
here along with HttpComponentsClientHttpRequestFactory
to execute a URL.
I have set up an HTTP request timeout (READ
and CONNECTION
time out) on my RestTemplate
by using HttpComponentsClientHttpRequestFactory
.
Here is my main code which is using the future and callables:
public class TimeoutThreadExample {
private ExecutorService executor = Executors.newFixedThreadPool(10);
// does it have to be static final?
private static final RestTemplate restTemplate = createRestTemplate();
// does this look right with the way I am creating `RestTemplate`?
private static RestTemplate createRestTemplate(){
// is it ok to create a new instance of HttpComponentsClientHttpRequestFactory everytime?
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setReadTimeout(READ_TIME_OUT);
requestFactory.setConnectTimeout(CONNECTION_TIME_OUT);
return new RestTemplate(requestFactory);
}
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;
}
}
Here is my Task
class which implements the Callable
interface and uses the 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;
}
}
Now I have everything working in my above code. Is the way I am creating RestTemplate
along with HttpComponentsClientHttpRequestFactory
thread-safe and efficient? Since RestTemplate
is very heavy to be created so not sure whether I have it right or not. I'd like to improve anything in creation of RestTemplate
with HttpComponentsClientHttpRequestFactory
.