1. 入门介绍

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

简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。

简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。

1.1 官网资料

https://github.com/Netflix/ribbon/wiki/Getting-Started
Ribbon目前也进入维护模式。
Ribbon未来可能被Spring Cloud LoadBalacer替代。

1.2 LB负载均衡(Load Balance)

简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高可用)。

常见的负载均衡有软件Nginx,LVS,硬件F5等。

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

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

集中式LB

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

进程内LB

将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。

Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

一句话

负载均衡 + RestTemplate调用
**

2. Ribbon负载均衡

2.1 架构说明

Ribbon其实就是一个软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和Eureka结合只是其中的一个实例。

Ribbon - 图1

Ribbon在工作时分成两步:

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

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

2.2 POM

先前工程项目没有引入spring-cloud-starter-ribbon也可以使用ribbon。

  1. <dependency>
  2. <groupld>org.springframework.cloud</groupld>
  3. <artifactld>spring-cloud-starter-netflix-ribbon</artifactid>
  4. </dependency>

这是因为spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-ribbon引用。

2.3 RestTemplate的使用

RestTemplate Java Doc

(1) getForObject() / getForEntity() - GET请求方法

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

  1. @GetMapping(value = "/consumer/payment/getEntity/{id}")
  2. public CommonResult<Payment> getEntity(@PathVariable("id") Long id){
  3. ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
  4. if(entity.getStatusCode().is2xxSuccessful()){
  5. return entity.getBody();
  6. }else{
  7. return new CommonResult<>(444,"操作失败");
  8. }
  9. }

(2) postForObject() / postForEntity() - POST请求方法

  1. @PostMapping(value = "/consumer/payment/createEntity")
  2. public CommonResult<Payment> createEntity(Payment payment){
  3. ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
  4. if(entity.getStatusCode().is2xxSuccessful()){
  5. return entity.getBody();
  6. }else{
  7. return new CommonResult<>(444,"操作失败");
  8. }
  9. }

3. Ribbon核心组件IRule

3.1 IRule:根据特定算法从服务列表中选取一个要访问的服务

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

Ribbon - 图2

3.2 Ribbon负载规则替换

(1)修改order80项目

(2)注意配置细节

官方文档明确给出了警告:

这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,

否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。

(也就是说不要将Ribbon配置类与主启动类同包)

(3)新建package - com.atguigu.myrule

image.png

(4)在com.lun.myrule下新建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. @Bean
  9. public IRule myRule(){
  10. return new RandomRule();
  11. }
  12. }

(5)主启动类

@RibbonClient(name = “CLOUD-PAYMENT-SERVICE”, configuration = MySelfRule.class)

  1. import com.lun.myrule.MySelfRule;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. import org.springframework.cloud.netflix.ribbon.RibbonClient;
  6. @SpringBootApplication
  7. @EnableEurekaClient
  8. //添加到此处
  9. @RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
  10. public class OrderMain80
  11. {
  12. public static void main( String[] args ){
  13. SpringApplication.run(OrderMain80.class, args);
  14. }
  15. }

(6)测试

开启cloud-eureka-server7001,cloud-consumer-order80,cloud-provider-payment8001,cloud-provider-payment8002

浏览器-输入http://localhost/consumer/payment/get/1

返回结果中的serverPort在8001与8002两种间反复横跳。

4. Ribbon负载均衡算法

4.1 原理

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

List instances = discoveryClient.getInstances(“CLOUD-PAYMENT-SERVICE”);

如:

List [0] instances = 127.0.0.1:8002
List [1] instances = 127.0.0.1:8001
8001+ 8002组合成为集群,它们共计2台机器,集群总数为2,按照轮询算法原理:

当总请求数为1时:1%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
当总请求数位2时:2%2=О对应下标位置为0,则获得服务地址为127.0.0.1:8002
当总请求数位3时:3%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
当总请求数位4时:4%2=О对应下标位置为0,则获得服务地址为127.0.0.1:8002
如此类推…

4.2 RoundRobinRule源码分析

  1. public interface IRule{
  2. /*
  3. * choose one alive server from lb.allServers or
  4. * lb.upServers according to key
  5. *
  6. * @return choosen Server object. NULL is returned if none
  7. * server is available
  8. */
  9. //重点关注这方法
  10. public Server choose(Object key);
  11. public void setLoadBalancer(ILoadBalancer lb);
  12. public ILoadBalancer getLoadBalancer();
  13. }
  1. package com.netflix.loadbalancer;
  2. import com.netflix.client.config.IClientConfig;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.util.List;
  6. import java.util.concurrent.atomic.AtomicInteger;
  7. /**
  8. * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
  9. *
  10. * @author stonse
  11. * @author Nikos Michalakis <nikos@netflix.com>
  12. *
  13. */
  14. public class RoundRobinRule extends AbstractLoadBalancerRule {
  15. private AtomicInteger nextServerCyclicCounter;
  16. private static final boolean AVAILABLE_ONLY_SERVERS = true;
  17. private static final boolean ALL_SERVERS = false;
  18. private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
  19. public RoundRobinRule() {
  20. nextServerCyclicCounter = new AtomicInteger(0);
  21. }
  22. public RoundRobinRule(ILoadBalancer lb) {
  23. this();
  24. setLoadBalancer(lb);
  25. }
  26. //重点关注这方法。
  27. public Server choose(ILoadBalancer lb, Object key) {
  28. if (lb == null) {
  29. log.warn("no load balancer");
  30. return null;
  31. }
  32. Server server = null;
  33. int count = 0;
  34. while (server == null && count++ < 10) {
  35. List<Server> reachableServers = lb.getReachableServers();
  36. List<Server> allServers = lb.getAllServers();
  37. int upCount = reachableServers.size();
  38. int serverCount = allServers.size();
  39. if ((upCount == 0) || (serverCount == 0)) {
  40. log.warn("No up servers available from load balancer: " + lb);
  41. return null;
  42. }
  43. int nextServerIndex = incrementAndGetModulo(serverCount);
  44. server = allServers.get(nextServerIndex);
  45. if (server == null) {
  46. /* Transient. */
  47. Thread.yield();
  48. continue;
  49. }
  50. if (server.isAlive() && (server.isReadyToServe())) {
  51. return (server);
  52. }
  53. // Next.
  54. server = null;
  55. }
  56. if (count >= 10) {
  57. log.warn("No available alive servers after 10 tries from load balancer: "
  58. + lb);
  59. }
  60. return server;
  61. }
  62. /**
  63. * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
  64. *
  65. * @param modulo The modulo to bound the value of the counter.
  66. * @return The next value.
  67. */
  68. private int incrementAndGetModulo(int modulo) {
  69. for (;;) {
  70. int current = nextServerCyclicCounter.get();
  71. int next = (current + 1) % modulo;//求余法
  72. if (nextServerCyclicCounter.compareAndSet(current, next))
  73. return next;
  74. }
  75. }
  76. @Override
  77. public Server choose(Object key) {
  78. return choose(getLoadBalancer(), key);
  79. }
  80. @Override
  81. public void initWithNiwsConfig(IClientConfig clientConfig) {
  82. }
  83. }

4.3 Ribbon之手写轮询算法

自己试着写一个类似RoundRobinRule的本地负载均衡器。

  • 7001/7002集群启动
  • 8001/8002微服务改造- controller ```java @RestController @Slf4j public class PaymentController{

    @GetMapping(value = “/payment/lb”) public String getPaymentLB() { return serverPort;//返回服务接口 }

    … }

  1. 80订单微服务改造<br />1.ApplicationContextConfig去掉注解@LoadBalancedOrderMain80去掉注解@RibbonClient
  2. ```java
  3. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.web.client.RestTemplate;
  7. @Configuration
  8. public class ApplicationContextConfig {
  9. @Bean
  10. //@LoadBalanced
  11. public RestTemplate getRestTemplate(){
  12. return new RestTemplate();
  13. }
  14. }

2.创建LoadBalancer接口

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 */
public interface LoadBalancer
{
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

3.MyLB
实现LoadBalancer接口

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 */
@Component//需要跟主启动类同包,或者在其子孙包下。
public class MyLB implements LoadBalancer
{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement()
    {
        int current;
        int next;

        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*****第几次访问,次数next: "+next);
        return next;
    }

    //负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ,每次服务重启动后rest接口计数从1开始。
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances)
    {
        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}

4.OrderController

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import com.lun.springcloud.lb.LoadBalancer;

@Slf4j
@RestController
public class OrderController {

    //public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    ...

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    ...

    @GetMapping(value = "/consumer/payment/lb")
    public String getPaymentLB()
    {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if(instances == null || instances.size() <= 0){
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri+"/payment/lb",String.class);

    }
}

5.测试 不停地刷新http://localhost/consumer/payment/lb,可以看到8001/8002交替出现。