12

In Spring Boot,for making a Rest Client call currently creating RestTemplate using the new keyword in multiple classes.

RestTemplate restTemplate = new RestTemplate(); 
ResponseEntity<String> response = restTemplate.exchange(

Planning to create a single class that returns a same instance of RestTemplate, and using it for all the Rest calls.

Will it affect performance. What may be the drawbacks on performance or any other?

Also instead of creating a single RestTemplate, is using Pooling a better option? Thanks

Rehan
  • 929
  • 1
  • 12
  • 29
  • Why don't you make use of Spring Dependency Injection? Inject the rest template through dispatcher servlet and autowire it, where ever required. – uday May 30 '16 at 04:55
  • Using Spring Boot. Plan to autowire the RestTemplate class where ever required. Had the question will using single RestTemplate through out affect performance or any other drawback? – Rehan May 30 '16 at 05:21
  • No it won't and probably will improve performance as you don't have the overhead of constructing the same object(s) over and over. – M. Deinum May 30 '16 at 05:44
  • Thanks Deinum. Also instead of using a single RestTemplate is creating RestTemplate pool a good idea? – Rehan May 30 '16 at 07:04
  • Use a single instance. Don't create another object, simply register it using @Bean for example in the configuration file and then inject as normal. – kab May 31 '16 at 18:46

1 Answers1

2

Creating a new RestTemplate every time you need to use it will be more expensive then just creating it once and using dependency injection to get a reference to it.

Creating a connection pool would provide an additional performance boost because it would allow connections to be re-used (if that is what you need)

mad_fox
  • 3,030
  • 5
  • 31
  • 43