本篇将继续接着上一篇 SpringCloud-服务注册 ,通过使用 DiscoveryClient 来实现服务发现,并且消费。
DiscoveryClient 源自于 spring-cloud-client-discovery ,是 spring cloud 中被定义用来服务发现的公共接口,在 spring cloud 的各类服务发现组件中,都有对应的实现,如 eureka、consul、zookeeper 。它提供从服务注册中心获取服务实例信息的能力。如果我们想自己实现一个服务发现组件,集成到spring cloud 中,就完全可以通过实现此接口来完成。
环境准备
类别 |
值 |
JDK
|
1.8.0_162
|
SOFABoot/SpringBoot
|
3.0.0/2.0.x.RELEASE
|
SpringCloud
|
Finchley.RC1
|
IDE
|
IDEA
|
工程背景
本案例使用 SOFABoot 3.0.x 版本集成 SringCloud F版。工程如下:
- sofa-eureka-consumer-discovery 服务消费方
本工程的父工程继续使用《SpringCloud-Eureka 服务注册》文中新建的父工程。
新建 sofa-eureka-consumer-discovery
这里我们通过 sofa-eureka-consumer-discovery 这个工程来手动发现服务。
右击 sofa-eureka-parent 父工程 -> New -> Module,这里选择 Maven 工程;
- artifactId:sofa-eureka-consumer-discovery。
修改 pom 文件
引入 spring-cloud-starter-netflix-eureka-client 依赖。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <parent> <artifactId>sofa-eureka-parent</artifactId> <groupId>com.alipay.sofa</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion>
<artifactId>sofa-eureka-consumer-discovery</artifactId>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies>
|
配置文件
1 2 3
| server.port=8088 spring.application.name=sofa-eureka-discovery eureka.client.serviceUrl.defaultZone=http:
|
启动类
1 2 3 4 5 6 7
| @SpringBootApplication @EnableEurekaClient public class SofaEurekaConsumerDiscoveryApplication { public static void main(String[] args) { SpringApplication.run(SofaEurekaConsumerDiscoveryApplication.class, args); } }
|
服务获取
这里通过 DiscoveryClient 对像手动获取到 HELLOSOFASERVICE 服务对应的所有实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @RestController public class DiscoveryController { @Autowired private DiscoveryClient discoveryClient;
@RequestMapping("/instance") public String getInstance(){ List<ServiceInstance> list = discoveryClient.getInstances("HELLOSOFASERVICE"); System.out.println("current service size = " + discoveryClient.getServices().size()); StringBuilder stringBuilder = new StringBuilder(); for( String s : discoveryClient.getServices()){ stringBuilder.append("services=" + s).append("\n"); List<ServiceInstance> serviceInstances = discoveryClient.getInstances(s); for(ServiceInstance si : serviceInstances){ stringBuilder.append("url=").append(si.getUri()).append("\n"); } } stringBuilder.append("instance num").append("=").append(list.size()); return stringBuilder.toString(); } }
|
启动 & 验证
启动当前工程,在此之前确保 注册中心和服务提供工程均已正常启动。然后在浏览器中输入:http:localhost:8088/instance

可以看到获取到的实例信息与注册中心上的实例信息是匹配的。