【问题标题】:how use application name replace ip:port about spring cloud eureka?spring cloud eureka如何使用应用程序名称替换ip:port?
【发布时间】:2017-11-02 04:46:59
【问题描述】:

spring cloud eureka问题:有3个微服务,1个eureka server,2个eureka client;

  1. 微服务A、B使用注解@EnableEurekaClient

  2. 微服务 A 有一个 RESTful api“http://localhost:8080/hi”。 api 返回“你好”。

  3. 现在,我调用 api ,使用 url "http://client/hi",但它不起作用。

  4. spring cloud eureka如何使用应用名称替换ip:port?

bootstrap.yml 内容:

spring:
  application:
    name: client

eureka:
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/

【问题讨论】:

    标签: spring-cloud netflix-eureka spring-cloud-netflix


    【解决方案1】:

    有很多方法可以做到这一点,这取决于您如何在代码中调用 REST API。

    如果您使用 RestTemplate 调用 API,则可以使用 @LoadBalanced RestTemplate 进行此操作

    在您想要调用 REST api 的代码中,请使用 @LoadBalanced 定义 RestTemplate,如下所示。

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

    当您调用 API 时,只需使用应用程序名称而不是 host:port,如下所示。

    this.restTemplate.getForObject("http://client/hi", String.class)
    

    如果您使用的是 SpringCloud Feign,您可以定义接口来调用您的 REST api,如下所示(不带 URL)

    @FeignClient(name="client")
    public interface ProductResource {
       : 
    }
    

    并在您的 Spring Boot 应用程序中添加注释 @EnableFeignClients,如下所示。

    @SpringBootApplication
    @EnableFeignClients
         : // other annotations you need.
    public class YourAPIInvokerApplication {
    

    在这两种方式中,你都需要添加一些依赖项。

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 1970-01-01
      • 2018-06-18
      • 2017-03-22
      • 2020-08-18
      • 2016-09-08
      • 2021-11-07
      • 2017-11-29
      • 2016-01-05
      相关资源
      最近更新 更多