目的:发现注册中心的服务,且进行消费。
服务发现的任务是由Eureka客户端完成,服务消费由Ribbon完成。
Ribbon简单介绍:
Ribbon是基于HTTP和TCP的客户端负载均衡器,可以在通过客户端配置的ribbonServerList服务端列表去轮询访问达到均衡负载的作用。
当其与Ribbon联合使用时,其ribbonServerList会被DiscoveryEnalbedNIWServerList重写,扩展成从Eureka注册中心获取服务端列表,将职责委托给Eureka来确定服务端是否已经启动。
1、首先创建新的SpringBoot基础工程,引入starter-netflix-ribbon、starter-netflix-eureka-client、starter-web等依赖
<!-- 包含嵌入式tomcat,springmvc等 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- ribbon 客户端负载均衡器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!-- eureka 服务注册依赖客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2、在应用程序入口处,通过
@EnalbeDiscoveryClient
注解,让该应用注册为Eureka客户端应用,来发现服务。
同时创建RestTemplate实例,并通过
@LoadBalanced
注解开启客户端负载均衡。
3、在应用程序创建ConsumerController类,并映射ribbon-consumer接口。
通过RestTemplate实现对HELLO-SERVICE服务提供接口调用,根据
服务名进行调用而不是具体的地址
。
@RestController
public class ConsumerController {
// 注入restTemplate
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
public String helloController() {
// 返回Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等
// hello-service 是服务名,不是一个具体的地址
}
}
4、同样在application.properties中配置Eureka服务注册中心的位置(与之前的hello-service一致)、端口号、服务名。
5、启动Eureka服务注册中心、启动两个不同端口的hello-service、启动改应用。
打开localhost:1111(Eureka服务中心),可以查看到2个hello-service、1个consumer服务。
访问ribbon-consumer接口,成功返回Hello World,同时在服务台中输出hello-service的服务列表情况(实例的位置、请求总数、第一次、上一次连接信息等等):
同时查看两个服务提供类的控制台交替输出服务信息:
完毕。