企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
如果多个微服务都注册到同一个Eureka中心,则任何一个微服务都可以看到自身和其他微服务的注册信息。 <br/> 目前在注册中心 cloud-eureka-server7001 我已经注册了两个微服务,下面演示通过其中的 cloud-provider-payment8001 微服务发现该注册中心的所有微服务注册信息。 <br/> 步骤如下: **1. 在 8001 的controller 层中添加 `DiscoveryClient` 组件** ```java @RestController @RequestMapping("/payment") public class PaymentController { @Autowired private DiscoveryClient discoveryClient; @GetMapping("/discovery") public Object discovery() { //获取所有已经注册到同一个Eureka中的微服务名,其实就是 spring.application.name 配置 List<String> services = discoveryClient.getServices(); List<String> registeryDetails = new ArrayList<>(1); services.forEach(service -> { //获取每个微服务下的所有实例 List<ServiceInstance> instances = discoveryClient.getInstances(service); instances.forEach(instance -> { String detail = "serviceId:" + instance.getServiceId() + ",instanceId:" + instance.getInstanceId() + ",host:" + instance.getHost() + ",port:" + instance.getPort() + ",url:" + instance.getUri() + ",schema:" + instance.getScheme() + ",metadata:" + instance.getMetadata(); registeryDetails.add(detail); }); }); return registeryDetails; } } ``` **2. 在 8001 的启动类上添加注解`@EnableDiscoveryClient`** ```java @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient //只有添加了该注解的模块才能被发现,否则不能 public class PaymentMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class,args); } } ``` **3. 重启 7001 Eureka 服务注册中心、8001 服务端** 访问 8001的url地址:http://localhost:8001/payment/discovery 得到了所有能被发现的微服务的注册信息。 ```json [ "serviceId:CLOUD-PAYMENT-SERVICE,instanceId:cloud-provider-payment8002,host:192.168.56.1,port:8002,url:http://192.168.56.1:8002,schema:null,metadata:{management.port=8002}", "serviceId:CLOUD-PAYMENT-SERVICE,instanceId:cloud-provider-payment8001,host:192.168.56.1,port:8001,url:http://192.168.56.1:8001,schema:null,metadata:{management.port=8001}" ] ```