我正在使用 spring cloud: Spring Boot Application with Eureka + Ribbon 默认配置。
我正在使用 2 RestTemplate
配置,都是@LoadBalanced
目前和他们都有相同的UriTemplateHandler
.
我声明了 @SpringBootApplication
还有 @RibbonClient(name="${service.name}")
注释。
我的问题是:
当我尝试访问第一个配置的 RestTemplate
时, RestTemplate
解析(通过 Eureka 和功能区负载平衡)到服务器,而不是我在 UriTemplateHandler
中配置的请求.
例如:在 UriTemplateHandler
我配置了“A-Service”并实时配置了 restTemplate
发送 httpRequest
到“B-服务”
这种行为经常发生,不仅针对特定请求,而且似乎仅在我访问第一个配置的 RestTemplate
时才会发生。 .
使用具有相同 uri 的 2 RestTemplate 是否有问题?
我不知道为什么会这样,请指教。
最佳答案
将这些 rest 模板创建为 bean 时,请为它们唯一命名,例如
@LoadBalanced
@Bean("integrationRestTemplate")
public RestTemplate restTemplate() throws Exception {
// build and return your rest template
return ....
}
然后,另一个可能没有任何特定名称,例如
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
现在,如果你有这两个不同的休息模板,你可以注入(inject)前一个,例如像那样:
@Service
public class MyService {
private final RestTemplate restTemplate;
public ApplicantService(@Qualifier("integrationRestTemplate") RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
// service methods
...
}
基本上,关键是您可以通过指定@Qualifier 来选择您想要的任何休息模板。
关于Spring Cloud 多个 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693858/