一、Ribbon概述

SpringCloud Ribbon 是基于Netflix Ribbon实现的一套客户端,负载均衡的工具。

简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用,Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是配置文件中列出Load Banlancer (简称LB) 后面所有的机器,Ribbon都会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。

官网: https://github.com/Netflix/ribbon/wiki/Getting-Started
Ribbon已经进入维护模式!未来的替换方案:Load Banlancer

1、Ribbon能作什么

1.1 LB (负载均衡)

LB 负载均衡 Load balance 是什么
简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
常见的负载均衡有软件 Nginx LVS 硬件F5等

常见的负载均衡算法

  • 轮询:为第一个请求选择健康池中的第一个后端服务器,然后按顺序往后依次选择,直到最后一个,然后循环。
  • 最小连接:优先选择连接数最少,也就是压力最小的后端服务器,在会话较长的情况下可以考虑采取这种方式。
  • 散列:根据请求源的 IP 的散列(hash)来选择要转发的服务器。这种方式可以一定程度上保证特定用户能连接到相同的服务器。如果你的应用需要处理状态而要求用户能连接到和之前相同的服务器,可以考虑采取这种方式。

Ribbon本地负载均衡客户端VS Nginx 服务端负载均衡区别

  • Nginx是服务器负载均衡,客户端所有请求都会交给Nginx,然后由Nginx实现转发请求,即负载均衡是由服务端实现的
  • Ribbon 本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术

1.1.2 集中式 LB

  • 集中式LB:即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5,也可以是软件,如Nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方。

1.1.3 进程内 LB

  • 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个何时的服务器。
  • Ribbon就属于是进程内LB, 它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

一句话总结Ribbon:Ribbon是实现负载均衡的一套客户端工具结合RestTemplate实现调用。

二、负载均衡演示

2.1 架构说明

总结:Ribbon其实就是一个软负载均衡的客户端组件。

它可以和其他所需请求的客户端结合使用,和eureka结合只是其中一个实例

image.png

2.1.1 Ribbon在工作室分成两步

  • 第一步先选择EurekaServer,它优先选择在同一个区域内负载较少的server
  • 第二部再根据用户指定的策略,再从server取到的服务注册列表中选择一个地址。

    其中Ribbon提供了多种策略:比如 轮询,随机和根据响应时间加权。

2.1.2 为什么没有引入Ribbon也可以完成负载均衡?

之前我们写样例的时候没有引入spring-cloud-start-ribbon也可以使用ribbon我们通过一个注解:@LoadBalanced赋予了RestTemplate负载均衡的能力;
原因是spring-boot-netfix-eureka-client自带了spring-starter-ribbon引用
image.png
因此我们不需要再次噖日Ribbon坐标,因为我们已经引入了spring-boot-netfix-eureka-client,里面自带Ribbon包。

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>

2.2. 二说RestTemplate的使用

为什么说它: 所谓的负载均衡,就是Ribbon结合RestTemplate实现调用微服务之间的调用。

2.2.1 getForObject方法/getForEntity方法

getForObject() // 返回对象为响应体中数据转化成的对象,基本上可以理解为JSON getForEntity() // 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等。

image.png

  1. ------------------ getForObject() --------------------------------------
  2. @GetMapping("/consumer/payment/get/{id}")
  3. public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
  4. // 返回对象为响应体中数据转化成的对象,基本上可以理解为JSO
  5. return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
  6. }
  7. ------------------ getForEntity() --------------------------------------
  8. /**
  9. * 测试getForEntity cloud-consumer-order80模块,OrderController类中
  10. */
  11. @GetMapping("/consumer/payment/getForEntity/{id}")
  12. public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
  13. // 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等。
  14. ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
  15. if (entity.getStatusCode().is2xxSuccessful()) {
  16. log.info(entity.getStatusCode() + "\t" + entity.getHeaders());
  17. return entity.getBody();
  18. }else {
  19. return new CommonResult<>(444, "操作失败");
  20. }
  21. }

image.png这些方法对应着各种HTTP状态码,可以用来判断返回的entity对象包含的是哪种状态码。
image.png 可以跑通。可以用entity获取更详细的信息,比如头信息,响应体,状态码等。
_log_.info(entity.getStatusCode() + "\t" + entity.getHeaders());

2.2.2 postForObject/postForEntity

  1. ----------------------------postForObject------------------------------
  2. @GetMapping("/consumer/payment/create")
  3. public CommonResult<Payment> create(Payment payment) {
  4. log.info("80收到的参数:" + payment.toString());
  5. return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
  6. }
  7. ----------------------------postForEntity------------------------------
  8. /**
  9. * 测试postForEntity cloud-consumer-order80模块,OrderController类中
  10. */
  11. @GetMapping("/consumer/payment/postForEntity/create")
  12. public CommonResult<Payment> create2(Payment payment) {
  13. log.info("80收到的参数:" + payment.toString());
  14. ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
  15. if (entity.getStatusCode().is2xxSuccessful()) {
  16. log.info(entity.getHeaders() + "\t" +entity.getStatusCode());
  17. return entity.getBody();
  18. } else {
  19. return new CommonResult<>(404, "操作失败");
  20. }
  21. }

使用postman测试
image.png
测试成功
image.png
数据库中也增加了相应数据image.png

三、Ribbon核心组件:IRule接口

3.1. IRule接口的各实现类,以及对应功能

根据特定算法从服务列表中选取一个要访问的服务。
image.png
IRule接口主要的实现类:
image.png

  • com.netflix.loadbalancer.RoundRobinRule:轮询
  • com.netflix.loadbalancer.RandomRule:随机
  • com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试
  • WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
  • BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
  • AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例
  • ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器

3.2. 如何替换负载均衡算法

①修改cloud-consumer-order80

②负载均衡配置类注意事项

注意配置类细节:官方文档明确给出了警告:这个自定义负载均衡配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。

什么是@ComponentScan

@SpringBootApplication注解中包含了@ComponentScan注解
image.png也就是说@SpringBootApplication标注的主配置类所在的包,以及所有子包都会被扫描到。image.png所以我们自定义的负载均衡配置类不能跟主启动类在同一个包下。

③新建com.atguigu.myrule包,将自定义负载均衡配置类MySelfRule放在改包下

写MySelfRule配置类

  1. package com.atguigu.myrule;
  2. import com.netflix.loadbalancer.IRule;
  3. import com.netflix.loadbalancer.RandomRule;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class MySelfRule
  8. {
  9. @Bean
  10. public IRule myRule()
  11. {
  12. return new RandomRule();//定义为随机负载均衡算法
  13. }
  14. }

④主启动类添加@RibbonCilent注解

name里面的内容表示指明访问xxx服务时使用复杂均衡,configuration表示指明负载均衡策略

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. //指明访问的服务CLOUD-PAYMENT-SERVICE,以及指定负载均衡策略
  4. @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
  5. public class OrderMain80 {
  6. public static void main(String[] args) {
  7. SpringApplication.run(OrderMain80.class, args);
  8. }
  9. }

⑤启动cloud-consumer-order80测试

image.png测试成功,访问http://localhost/consumer/payment/get/31 也可以

四、负载均衡算法

4.1 原理

轮循负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务重启后rest接口计数从1开始。

  1. List<ServiceInstance> instances = doscoveryClient.getInstances("cloud-payment-service");
  2. 比如集群中有两台服务器,地址分别为:
  3. List[0] instances = 127.0.0.1:8002;
  4. List[1] instances = 127.0.0.1:8001;
  5. 8001 + 8002 组合为集群,他们共计2台机器,集群总数为2,按照轮询算法原理:
  6. 当总请求数为1时:1 % 2 = 1,对应下标为 1,则获得服务地址为 127.0.0.18001
  7. 当总请求数为2时:2 % 2 = 0,对应下标为 0,则获得服务地址为 127.0.0.18002
  8. 当总请求数为3时:3 % 2 = 1,对应下标为 1,则获得服务地址为 127.0.0.18001
  9. 当总请求数为4时:4 % 2 = 0,对应下标为 0,则获得服务地址为 127.0.0.18002
  10. 如此类推

4.2 源码

原理+JUC(CAS+自旋锁的复习)

4.3 手写一个负载均衡算法

①8001/8001微服务改造:controller

  1. @GetMapping(value = "/payment/lb")
  2. public String getPaymentLB()
  3. {
  4. return serverPort;
  5. }

②80微服务改造

ApplicationContextConfig去掉@LoadBalance注解

③创建LoadBalancer接口

新建com.atguigu.springcloud.lb包

  1. public interface LoadBalancer {
  2. ServiceInstance instances(List<ServiceInstance> serviceInstances);
  3. }

④创建LoadBalancer接口的实现类MyLoadBalancer

  1. @Component
  2. public class MyLoadBalancer implements LoadBalancer{
  3. private AtomicInteger atomicInteger = new AtomicInteger(0);
  4. public final int getAndIncrement() {
  5. int current;
  6. int next;
  7. //从下面的分析中得知:该循环主要是得到next值,单机是每循环一次返回一次next
  8. //高并发时:就不是这种情况了。因为数字会被抢占。
  9. //自旋锁
  10. do {
  11. current = this.atomicInteger.get();
  12. //考虑到极端情况,atomicInteger最大值为2147483647
  13. //当请求次数超过这个值的时候,从0开始
  14. next = current >= 2147483647 ? 0 : current + 1;
  15. //compareAndSet方法使用了CAS机制,判断current是否变化,如果变了自旋,反之更新current
  16. /**
  17. * 当atomicInteger=0时,current=0, next=1
  18. * atomicInteger和current进行比较,相等时返回true将atomicInteger更新为next,1,取反跳出循环,再返回next
  19. * 当atomicInteger=2147483647时,current=2147483647,next=0
  20. * atomicInteger和current进行比较,相等时返回true将atomicInteger更新为next, 0,取反跳出循环,再返回next
  21. *
  22. * 如果是高并发时,则需要判断当前线程获得的current值跟atomicInteger的值是否相等,
  23. * 如果不相等则表示其他线程已经操作了atomicInteger,自旋。
  24. * 这就是乐观锁的一个实现
  25. */
  26. }while (!this.atomicInteger.compareAndSet(current, next));
  27. System.out.println("************第几次访问次数:" + next);
  28. return next;
  29. }
  30. //负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标
  31. // 每次服务重启动后rest接口计数从1开始。
  32. @Override
  33. public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
  34. //计算当前访问应该分配给哪台服务器处理
  35. int index = getAndIncrement() % serviceInstances.size();
  36. //返回目标服务器
  37. return serviceInstances.get(index);
  38. }
  39. }

⑤修改OrderController

  1. @Resource //自动注入自定义的MyLoadBalancer类
  2. private LoadBalancer loadBalancer;
  3. @Resource
  4. private DiscoveryClient discoveryClient;
  5. /**
  6. * 测试自己的轮循算法
  7. */
  8. @GetMapping(value = "/consumer/payment/lb")
  9. public String getPaymentLB() {
  10. List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
  11. if (instances == null || instances.size() <= 0) {
  12. return null;
  13. }
  14. ServiceInstance serviceInstance = loadBalancer.instances(instances);
  15. URI uri = serviceInstance.getUri();
  16. return restTemplate.getForObject(uri + "/payment/lb", String.class);
  17. }

⑥测试

image.pngimage.png