I'm constructing a RestTemplate
object once within a @PostConstruct
method and using that instance to make all HTTP calls from my app. For example:
@Service
public class MicroserviceIntercomm {
private RestTemplate restTemplate;
private @Autowired RequestBean requestBean; //RequestScope
@PostConstruct
public void init() throws IllegalArgumentException, UnsupportedEncodingException, NoSecretProvidedException, NoAlgorithmSetException, GenerateTokenException, InvalidEndpointException {
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
clientHttpReq.setConnectTimeout(connectionTimeout);
clientHttpReq.setReadTimeout(readTimeout);
restTemplate = new RestTemplate(clientHttpReq);
}
public void apiCallFoo() {
headers.set(headerName, requestBean.getJwtToken());
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
}
public void apiCallBar() {
headers.set(headerName, requestBean.getJwtToken());
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
}
}
From the documentation it isn't clear whether or not using RestTemplate
this way is thread-safe.
According to this blog article it is:
This means, for instance, that the RestTemplate is thread-safe once constructed, and that you can use callbacks to customize its operations.
However, when viewing the Javadocs for the exchange()
method, it isn't explicitly listed that the method is thread-safe.
Should we make changes to this code to make it thread-safe, or does it work as intended?
We're using Spring boot 1.5.10.RELEASE.