zl程序教程

您现在的位置是:首页 >  其他

当前栏目

SpringCloud学习(七):服务发现Discovery

2023-03-14 22:47:49 时间

如果我们想获得在eureka上注册的服务的信息,比如服务名称、端口号之类的信息,需要用到服务发现Discovery。


一、在服务上增加DiscoveryClient属性


       

在8001和8002服务的PaymentController类里增添DiscoveryClient属性

1. @Autowired
2. private DiscoveryClient discoveryClient;


二、再写一个方法用来在浏览器和后台返回服务的信息



@GetMapping(value = "/payment/discovery")
    public Object getDiscovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("======element:"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "	" + instance.getHost() + "	"
                    + instance.getPort() + "	"+ instance.getUri());
        }
        return this.discoveryClient;
    }


三、在主启动类上增加@EnableDiscoveryClient注解



1084b36e0100446c920f1b6f96c75ad1.png


四、8002服务与8001服务的改动一致 



五、运行测试



浏览器地址栏输入

http://localhost:8001/payment/discovery

aeb9a2203f204b71969c80b0279a208d.png

可以看出打印出服务的各种信息

输入 http://localhost:8002/payment/discovery 也是如此