一、什么是服务发现
简单来说:服务发现有三个角色,服务提供者、服务消费者和服务中介。服务中介是联系服务提供者和服务消费者的桥梁。
服务提供者将自己提供的服务地址注册到服务中介,服务消费者从服务中介那里查找自己想要的服务地址,然后使用这个服务。
服务中介提供多个服务,每个服务对应多个服务提供者。服务中介就是一个字典,字典里有很多key-value键值对,key是服务名称,value是服务提供者的地址列表。服务注册就是调用字典的put方法放东西,服务查找就是调用字典的get方法获取东西。当服务提供者新加入时,要求服务中介能及时告知服务消费者。
二、服务发现实现
对于注册进euerka里面的微服务,可以通过服务发现来获得该服务的信息。
基于之前的项目,我们以cloud-provider-payment8001
为例进行修改实现:
1)修改8001的PaymentController
,添加springframework
包下的DiscoveryClient
注解注入:
@Resource private DiscoveryClient discoveryClient;
再添加一个Get请求方法:
@GetMapping(value = "/payment/discovery") public Object discovery(){ // 获取所有服务 List<String> services = discoveryClient.getServices(); // 遍历服务 for (String service : services) { System.out.println("service: " + service); } // 获取服务ID为CLOUD-PAYMENT-SERVICE中的所有实例 List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"); // 遍历实例 for(ServiceInstance instance: instances){ System.out.println(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri() + "\t"); } return this.discoveryClient; }
2)修改主启动类,在主启动类PaymentMain8001
上加上@EnableDiscoveryClient
注解:
package com.panziye.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient @EnableDiscoveryClient public class PaymentMain8001 { public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class,args); } }
3)测试
先启动7001、7002、7003服务注册中心,再启动8001、8002和80模块,然后访问http://localhost:8001/payment/discovery
测试:
查看IDEA后台日志打印:
通过日志我们可以清楚地看到Eureka注册中心中所有的微服务实例的信息,因此服务发现可以帮助我们获得相关服务的信息。