首页 > 解决方案 > 使用来自发现而不是目录主机的 ServiceID 的微服务之间的通信?

问题描述

我是新的微服务,我正在阅读一些关于发现服务器的示例,我看到我们可以使用 url 调用另一个微服务 api,例如: http://inventory-service/api/inventory/{productCode}。“inventory-service”是我在发现中注册的一个服务实例。所以我的问题是使用 serviceId 而不是调用目录 host:port: http://localhost:9009/api/inventory/ {productCode} 有什么好处。

标签: spring-cloudnetflix-eurekaservice-discovery

解决方案


假设您通过在 src/main/resources/bootstrap.properties 中配置 Eureka serviceUrl 向 Eureka 服务器注册 inventory-service。

 spring.application.name=inventory-service
 eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

然后构建库存服务并通过运行以下命令启动它的 2 个实例。

 java -jar -Dserver.port=9001 target/inventory-service-0.0.1-SNAPSHOT-exec.jar

 java -jar -Dserver.port=9002 target/inventory-service-0.0.1-SNAPSHOT-exec.jar

当您访问 Eureka Dashboard http://localhost:8761/时,您将看到已注册的 2 个库存服务实例。

如果您想从您的消费者应用程序应用客户端负载平衡,您需要这样的配置:

 server.ribbon.listOfServers=localhost:9001,localhost:9002 
 server.ribbon.eureka.enabled=false

如果您想启动新实例,则需要在您的使用者配置中注册它们。

使用 ServiceID,您不必担心,因为所有实例都将使用相同的标识符进行注册。它将自动添加到可用服务器列表中。这是使用 ServiceId 而不是主机名的优点之一


推荐阅读