Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cloud multiple RestTemplate

I am using spring cloud: Spring Boot Application with Eureka + Ribbon default configuration.

I am using 2 RestTemplate configurations, both are @LoadBalanced currently and both of them have the same UriTemplateHandler.

I declared both the @SpringBootApplication and also the @RibbonClient(name="${service.name}") annotations.

My problem is:

When I am trying to access the first configured RestTemplate, the RestTemplate resolvs (by eureka and load balancing by ribbon) to a server , not as I requested as configured in the UriTemplateHandler.

For example: in the UriTemplateHandler I configured "A-Service" and in real time the restTemplate sends the httpRequest to "B-Service" This behavior happens often, not just for a specific request, but it looks like it only happens when I'm accessing the first configured RestTemplate.

Is it a problem to use 2 RestTemplate with the same uri?

I have no idea why it happens, please advise.

like image 978
Edna Avatar asked Oct 16 '25 18:10

Edna


1 Answers

When creating these rest templates as beans, name them uniquely, like e.g.

@LoadBalanced
@Bean("integrationRestTemplate")
public RestTemplate restTemplate() throws Exception {
   // build and return your rest template 
   return ....
}

Then, the other one might be without any specific name e.g.

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Now, if you have these two distinctive rest templates, you can inject the former one e.g. like that:

@Service
public class MyService {

    private final RestTemplate restTemplate;

    public ApplicantService(@Qualifier("integrationRestTemplate") RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

// service methods
...
}

Basically, the point is you can choose whatever rest template you want, by specifying a @Qualifier.

like image 92
grzeshtoph Avatar answered Oct 18 '25 11:10

grzeshtoph