版权声明:喜欢的点个赞吧!欢迎转载,请注明出处来源,博文地址: https://blog.csdn.net/u012294515/article/details/87865113
前言
前几章节实现了微服务的注册与发现,Eureka Client 会把自己注册到Eureka Server 上,然而一般在生产环境中,各个微服务都会部署多个实例,那么服务消费者如何将请求分摊到多个服务的提供者实例上呢?
Ribbon 简介
Ribbon
是Netflix
发布的客户端负载均衡器,有助于控制HTTP
和TCP
客户端的行为。Spring Cloud Ribbon
虽然只是一个工具类框架,它不像服务注册中心、配置中心、API
网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud
构建的微服务和基础设施中。微服务间的调用,API
网关的请求转发等内容,实际都是通过Ribbon
来实现的,包括后续我们将要介绍的Feign
,它是基于Ribbon
实现的工具。
负载均衡
负载均衡(
Load Balance
)是分布式系统架构设计中必须考虑的因素之一,它通常是指,将请求/数据【均匀】分摊到多个操作单元上执行,负载均衡的关键在于【均匀】。
为服务消费者整合Ribbon
前提: 在第二章节中我们已经写好了注册中心Eureka
和服务的提供者Client
,将它们启动,并访问。
- 创建一个
eureka-consumer-ribbon
服务消费者工程。 pom
文件修改,引入Ribbon
...
<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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
...
- 修改启动类
RibbonApplication.java
,通过@EnableDiscoveryClient
注册为Eureka客户端应用,以获得服务发现的能力。同时创建RestTemplate
的Spring Bean 实例,通过@LoadBalanced
注解开启客户端负载均衡
@SpringBootApplication
@EnableDiscoveryClient
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
- 创建
ConsumerContorller
类,并实现Client
的接口(注:Client的接口参考第二章)。通过上面创建的RestTemplate
来实现对Client
服务提供的/msg接口进行调用。可以看到这里访问的地址填写的是服务名client
而不是一个具体的地址,在服务治理框架中这是一个非常重要的特性。
@RestController
public class ConsumerContorller {
@Autowired
RestTemplate restTemplate;
@GetMapping("/ribbon")
public String helloConsumer(@RequestParam("name") String name){
return restTemplate.getForEntity("http://client/msg?name="+name,String.class).getBody();
}
}
- 编写配置文件
application.yml
spring:
application:
#客户端名称
name: consumer-ribbon
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
server:
port: 8881
- 启动
consumer-ribbon
后就可以在Eureka界面上看到服务已经注册成功。
- 在浏览器访问
http://localhost:8881/ribbon?name=ribbon
。可以看到浏览器上返回了信息:hello~ ribbon! welcome spring cloud.8081
,再按一次返回了信息:hello~ ribbon! welcome spring cloud.8082
,原因是启动了两个client,端口分别为8081、8082。Ribbon
将请求分别向两个客户端轮训发送,这个就是客户端的负载均衡。
可以在consumer-ribbon
的应用控制台看到如下信息,Ribbon
输出了当前客户端维护的Client
的服务列表情况,其中包含了各个实例的位置,Ribbon
就是按照此信息进行轮训访问的,以实现基于客户端的负载均衡。另外还输出了一些其他非常有用的信息,如对各个实例的请求总数量,第一次连接信息、上一次连接信息、总的请求失败数量等。
小结
本章简单的说明了如何通过Ribbon实现客户端的负载均衡,还有许多的配置这里就不一一说明了,下一章打算写下通过Fegin实现服务端的负载均衡~