Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to keep RestTemplate in memory than creating new RestTemplate with every request?

Tags:

java

Is it better to keep RestTemplate in memory than creating new RestTemplate with every request ?

Example: With every request in my api, my api request to another api with REST. So my method can look like this :

exampleMethod() {
   RestTemplate restTemplate = new RestTemplate;
   restTemplate.getForObject(...);
}

or :

private RestTemplate restTemplate;

exampleMethod() {
   if(restTemplate == null) {
      restTemplate = new RestTemplate;
   }
   restTemplate.getForObject(...)
}
like image 571
Kenez92 Avatar asked Oct 31 '25 17:10

Kenez92


1 Answers

RestTemplate is designed to be thread-safe and reusable.

RestTemplate is just a facade that doesn't perform actual network operations. It delegates network operations to a HTTP client implementation. This HTTP client implementation can be expensive to create and often handles network level optimizations e.g. caching of connections per origin. You usually want to reuse this HTTP client implementation and this can be achieved by reusing RestTemplate.

Normally you would create RestTemplate as a singleton bean within Spring context. Especially in Spring Boot this is important and you shouldn't use new RestTemplate() syntax because it will not inject all registered customizers.

like image 171
Karol Dowbecki Avatar answered Nov 02 '25 06:11

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!