Spring Cloud 多个 RestTemplate

标签 spring cloud resttemplate netflix-ribbon

我正在使用 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/

相关文章:

java - Groovy/Java : Parallel processing of directory structure where each node is a list of subdirectories/files

带有 Spring Resttemplate : Error messageConverter 的 Android

java - Spring RestTemplate 415 不支持的媒体类型

java - 如何在 Spring 中为 MQSeries 创建 TopicConnectionFactory?

cloud - 为 OpenNebula 创建图像

java - 尝试在多个实例上运行批处理作业时出现 DuplicateKey 异常

google-cloud-platform - Cloud Composer v2 API 服务代理扩展角色可能缺失

java - 带请求参数的 RestTemplate POST 请求

java - spring-framework-bom :jar:4. 0.1.RELEASE 的 netbeans maven Web 应用程序中的依赖项解析异常

spring-boot+thymeleaf crud :edit a row