Ribbon负载均衡与原理解析

Ribbon负载均衡服务调用

在这里插入图片描述

简介

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


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

负载均衡

1.什么是负载均衡

Load balancing,即负载均衡,是一种计算机技术,用来在多个计算机(计算机集群)、网络连接、CPU、磁盘驱动器或其他资源中分配负载,以达到最优化资源使用、最大化吞吐率、最小化响应时间、同时避免过载的目的。
常见的负载均衡有软件:Nginx ,LVS 硬件 F5等

2.为什么需要负载均衡

我们在日常生活中经常免不了要去一些比较拥挤的地方,比如地铁站、火车站、电影院、银行等。无论是买票,还是排队入场,这些场所一般都会设置多个服务点或者入口的。如果没有人引导的话,大多数情况下,最近的入口会挤满人。而哪些距离较远的服务点或者入口就宽松很多。

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

Nginx 是服务器负载均衡,客户端所有的请求都会交给nginx ,然后由nginx实现转发请求。即负载均衡是由服务端实现的

Ribbon本地负载均衡,在调用微服务接口的时候,会在注册中心上获取服务列表之后缓存到JVM本地,从而本地实现RPC远程待哦用的技术

在这里插入图片描述
在这里插入图片描述
Ribbon 在工作时分成两步

第一步先选择EurekaServer , 它优先选择在同一区域内负载较少的Server。第二步在根据用户指定的策略,它从server取到的服务注册列表中选择一个地址。其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。


在我们新版的 netflix-eureka-client 中已经集成了Ribbon
在这里插入图片描述

 <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

Ribbon核心组件IRUle

在这里插入图片描述
他是一个接口

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.netflix.loadbalancer;

public interface IRule {
    Server choose(Object var1);

    void setLoadBalancer(ILoadBalancer var1);

    ILoadBalancer getLoadBalancer();
}

Ribbon 常见的负载算法:

  • 默认为RoundRobinRule轮询。

在这里插入图片描述


替换Ribbon负载算法

在这里插入图片描述
Ribbon的自定义配置类不可以放在@ComponentScan所扫描的当前包下以及子包下,否则这个自定义配置类就会被所有的Ribbon客户端共享,达不到为指定的Ribbon定制配置,而@SpringBootApplication注解里就有@ComponentScan注解,所以不可以放在主启动类所在的包下。(因为Ribbon是客户端(消费者)这边的,所以Ribbon的自定义配置类是在客户端(消费者)添加,不需要在提供者或注册中心添加)

1.新建包Ribbon 不能和启动类在一个包
在这里插入图片描述

package com.yxl.ribbon;

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 myRule(){
        return new RandomRule();    //负载均衡机制改为随机
    }
}

2.在启动类加入注解

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

  • name为指定的服务名(服务名必须与注册中心显示的服务名大小写一致)
  • configuration为指定服务使用自定义配置(自定义负载均衡机制)

Ribbon负载均衡算法原理

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

  • 如: List [0] instances = 127.0.0.1:8001
            List [1] instances = 127.0.0.1:8002

  • 8001 + 8002 组合成为集群,他们共计2台机器,集群总数为2,按照轮询算法原理 :

当请求数为1时: 1%2=1 对应下标1 则请求 8002 机器
当请求数为1时: 2%2=0 对应下标0 则请求 8001 机器
当请求数为1时: 3%2=1 对应下标1 则请求 8002 机器
当请求数为1时: 4%2=0 对应下标0 则请求 8001 机器
如此类推…

RoundRobinRule源码
/*
 *
 * Copyright 2013 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.netflix.loadbalancer;

import com.netflix.client.config.IClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
 *
 * @author stonse
 * @author Nikos Michalakis <nikos@netflix.com>
 *
 */
 //继承 AbstractLoadBalancerRule
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() {
    // 初始化AtomicInteger 原子类 0
        nextServerCyclicCounter = new AtomicInteger(0);
    }

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

    public Server choose(ILoadBalancer lb, Object key) {
    //判断传来的负载是否为 null
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        }

        Server server = null;
        int count = 0;
        //满足条件
        while (server == null && count++ < 10) {
        //只有已启动且可访问的服务器
            List<Server> reachableServers = lb.getReachableServers();
            //获取所有的服务器
            List<Server> allServers = lb.getAllServers();
            //长度
            int upCount = reachableServers.size();
            int serverCount = allServers.size();
			// 如果等于 0 return
            if ((upCount == 0) || (serverCount == 0)) {
                log.warn("No up servers available from load balancer: " + lb);
                return null;
            }
//取余操作
            int nextServerIndex = incrementAndGetModulo(serverCount);
            //获取下标
            server = allServers.get(nextServerIndex);
			//如果server ==null 设置优先级
            if (server == null) {
                /* Transient. */
                Thread.yield();
                //结束本次循环 继续下次循环
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

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

    /**
     * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
     *
     * @param modulo The modulo to bound the value of the counter.
     * @return The next value.
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % modulo;
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}


 private int incrementAndGetModulo(int modulo) {
    	//CAS加自旋锁
    	//CAS(Conmpare And Swap):是用于实现多线程同步的原子指令。CAS机制当中使用了3个基本操作数:内存地址V,旧的预期值A,要修改的新值B。更新一个变量的时候,只有当变量的预期值A和内存地址V当中的实际值相同时,才会将内存地址V对应的值修改为B。
    	//自旋锁:是指当一个线程在获取锁的时候,如果锁已经被其它线程获取,那么该线程将循环等待,然后不断的判断锁是否能够被成功获取,直到获取到锁才会退出循环。 
        for (;;) {
        	//获取value,即0
            int current = nextServerCyclicCounter.get();
            //取余,为1
            int next = (current + 1) % modulo;
            //进行CAS判断,如果此时在value的内存地址中,如果value和current相同,则为true,返回next的值,否则就一直循环,直到结果为true
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
    }

AtomicInteger的compareAndSet方法:

public class AtomicInteger extends Number implements java.io.Serializable {
	...
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
    ...
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值