SpringCloud03_Ribbon的概述、核心组件IRule、负载均衡算法底层原理、手写Ribbon轮询算法

①. Ribbon的概述

  • ①. Ribbon是Netfix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用

  • ②. Ribbon目前也进入维护模式(未来替换方案)
    在这里插入图片描述

  • ③. LB(负载均衡):简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
    Nginx(集中式):我们可以将它比喻成进入学校的大门
    Ribbon(进程式):进入大门后,进去哪个班级

②. 再谈RestTemplate

  • ①. 架构说明:Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例
    在这里插入图片描述
  • ②. pom文件说明

补充说明:
(1). 之前写样例时候没有引入spring-cloud-starter-ribbon也可以使用ribbon
在这里插入图片描述
(2). 猜测spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-ribbon引用,证明如下:可以看到spring-cloud-starter-netflix-eureka-client 确实引入了Ribbon
在这里插入图片描述

在这里插入图片描述

③. Ribbon核心组件IRule

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

在这里插入图片描述

  • ②. 修改cloud-consumer-order80
    官方文档明确给出了警告:
    这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了
    在这里插入图片描述
  • ③. 新建package(com.atguigu.myrule)
    一定要注意这里的@LoadBalanced一定不能注释掉
    如果注释了会报如下错误

    在这里插入图片描述
@Configuration
public class ApplicationContextConfig{
	@Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
   		 return new RestTemplate();   
    }
}
package com.atguigu.myrule;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MySelfRule {
    @Bean
    public IRule getRule(){
       return new RandomRule();
    }
}
  • ④. 主启动类添加@RibbonClient
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}
  • ⑤. 测试:http://localhost/consumer/payment/get/31
    我们可以看到会按照我们预期的效果随机的方式进行

④. Ribbon负载均衡算法底层原理

  • ①. 理论知识点:
    在这里插入图片描述
  • ②. 源码分析(掌握)
    Ribbon默认使用的负载均衡是轮询,IRule的一个具体实现类是使用轮询算法;在这里类里面,有一个原子整型类AtomicInteger,它会在无参构造函数中进行一个初始化的操作。我们会去调用它的choose方法查看使用负载均衡时候使用的是哪个Server;如果你当前参数传入进行的这个ILoadBalancer==null,就直接retrun null;如果不为null,那么先将server=null;然后调用它的获取健康服务的方法和获取所有服务的方法;得到这两个方法的size;如果说这两个size都不为0;那么我们就将所有服务的size作为参数传入进一个方法中;这个方法使用的是CAS的思想+自旋锁;将原子整型类AtomicInteger中的参数获取到为0; 我们将获取到的参数+1 % 传入这个方法的参数也就是集群的总量,获取到index,这个index就是我们轮询算法会去选择那个Server;进行比较并交换的处理,比较成功! 那么就return index;获取到index后,通过集合中的get(index)方法获取到具体要执行那个端口号的Server
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.netflix.loadbalancer;

import com.netflix.client.config.IClientConfig;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RoundRobinRule extends AbstractLoadBalancerRule {
    private AtomicInteger nextServerCyclicCounter;
    private static final boolean AVAILABLE_ONLY_SERVERS = true;
    private static final boolean ALL_SERVERS = false;
    private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);

    public RoundRobinRule() {
        this.nextServerCyclicCounter = new AtomicInteger(0);
    }

    public RoundRobinRule(ILoadBalancer lb) {
        this();
        this.setLoadBalancer(lb);
    }

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        } else {
            Server server = null;
            int count = 0;

            while(true) {
                if (server == null && count++ < 10) {
                    List<Server> reachableServers = lb.getReachableServers();
                    List<Server> allServers = lb.getAllServers();
                    int upCount = reachableServers.size();
                    int serverCount = allServers.size();
                    if (upCount != 0 && serverCount != 0) {
                        int nextServerIndex = this.incrementAndGetModulo(serverCount);
                        server = (Server)allServers.get(nextServerIndex);
                        if (server == null) {
                            Thread.yield();
                        } else {
                            if (server.isAlive() && server.isReadyToServe()) {
                                return server;
                            }

                            server = null;
                        }
                        continue;
                    }

                    log.warn("No up servers available from load balancer: " + lb);
                    return null;
                }

                if (count >= 10) {
                    log.warn("No available alive servers after 10 tries from load balancer: " + lb);
                }

                return server;
            }
        }
    }

    private int incrementAndGetModulo(int modulo) {
        int current;
        int next;
        do {
            current = this.nextServerCyclicCounter.get();
            next = (current + 1) % modulo;
        } while(!this.nextServerCyclicCounter.compareAndSet(current, next));

        return next;
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

⑤. 手写Ribbon轮询算法

  • ①. 7001/7002集群启动

  • ②. 8001/8002微服务改造controller

@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
    return serverPort;
}
  • ③. 80订单微服务改造
  1. ApplicationContextBean去掉@LoadBalanced
  2. LoadBalancer接口
package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {
     //收集服务器总共有多少台能够提供服务的机器,并放到list里面
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
  • ③. MyLB
package com.atguigu.springcloud.lb;

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);

    //坐标
    private 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;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {  //得到机器的列表
       int index = getAndIncrement() % serviceInstances.size(); //得到服务器的下标位置
        return serviceInstances.get(index);
    }
}
  • ④. OrderController
@RestController
@Slf4j
public class OrderController {

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

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment>   create( Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);  //写操作
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/payment/getForEntity/{id}")
     public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()){
          //  log.info(entity.getStatusCode()+"\t"+entity.getHeaders());
            return entity.getBody();
        }else {
            return new CommonResult<>(444,"操作失败");
        }
     }

    @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);
    }
}
  • ⑤. 测试 :http://localhost/consumer/payment/lb
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

所得皆惊喜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值