Springcloud-Alibaba 〖七〗Ribbon篇 打開源碼 手寫負載均衡算法

PS: github倉庫倉庫地址項目都放到裏面了

一. Ribbon 是什麼?

Spring Cloud Ribbon 是基於Netflix Ribbon 實現的一套客戶端 負載均衡的工具。

Ribbon 是 Netflix 發佈的開源項目,主要功能是提供客戶端的軟件負載均衡算法和服務調用。Ribbon 客戶端組件提供一系列完善的配置項如連接超時,重試等。簡單的說,就是在配置文件中列出 Load Balancer(簡稱LB)後面所有的機器,Ribbon 會自動的幫助你基於某種規則(如簡單輪詢、隨機連接等)去連接這些機器。我們很容易使用Ribbon實現自定義的負載均衡算法。

二. LB負載均衡(Load Balance)

簡單的說就是將用戶的請求平攤的分配到多個服務上,從而達到系統的HA(高可用)。常見的負載均衡有軟件 Nginx,LVS,硬件F5 等。

  • 集中式B
    即在服務的消費方和提供方之間使用獨立的LB設施(可以是硬件,如F5,也可以是軟件,如nginx),由該設施負責把訪問請求通過某種策略轉發至服務的提供方
  • 進程內LB
    將 LB 邏輯集成到消費方,消費方從服務註冊中心獲知有哪些地址可用,然後自己再從這些地址中選擇出一個合適的服務器。Ribbon就屬於進程內 LB ,它只是一個類庫,集成與消費方進程,消費方通過它來獲取到服務提供方的地址。

Ribbon 就是 負載均衡 + RestTemplate調用,最終實現RPC的遠程調用。

三. Ribbon架構

在這裏插入圖片描述
由於eureka天生集成了ribbon,所以可以不用添加依賴就可以用ribbon
在這裏插入圖片描述

四. RestTemplate調用

4.1 getForObject()方法


    @GetMapping("/consumer/payment/getEntity/{id}")
    public CommonResult<Payment> getForEntity(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if ((forEntity.getStatusCode().is2xxSuccessful())){
            return forEntity.getBody();
        }else {
            return new CommonResult<>(444,"調用失敗");
        }
    }

getForObject可以獲取返回的更多信息,包括請求頭,請求狀態碼,等等.
在這裏插入圖片描述
測試
在這裏插入圖片描述

4.2 getForObject()方法

  • getForObject()其實比getForEntity()多包含了將HTTP轉成POJO的功能,但是getForObject沒有處理response的能力。因爲它拿到手的就是成型的pojo。省略了很多response的信息。

調用

@GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        log.info("*******消費者啓動創建訂單*******");
        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);
    }

測試結果
在這裏插入圖片描述

五. Ribbon的負載均衡機制 IRule

默認採用輪詢機制
在這裏插入圖片描述

5.1 目錄結構

在這裏插入圖片描述

5.2 創建規則類

這個自定義配置類不能放在 @ComponentScan 所掃描的當前包下以及子包下,否則自定義的配置類就會被所有的 Ribbon 客戶端所共享,達不到特殊化定製的目的了。所以我們在java目錄下新建 com.atguigu.myrule.MyselfRule類,這裏我們創建出隨機規則

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 myRule(){
        return new RandomRule(); //定義爲隨機
    }
}

5.3 主啓動類添加註解

在這裏插入圖片描述

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

5.4 測試

在這裏插入圖片描述
在之前輪詢的情況下端口是8001與8002交替出現,而負載均衡規則變爲隨機後,端口是隨機出現的

六. 負載均衡算法

6.1 負載均衡算法: 輪詢

  • rest 接口第幾次請求數 % 服務器集羣總數量 = 實際調用服務器位置下標

  • 每次服務器重啓後rest接口數從1開始

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

  1. List[0] instances = 127.0.0.1:8002

  2. List[1] instances = 127.0.0.1:8001

例如我們現在有兩臺機子去負載均衡

請求次數 計算公式 取得下標
1 1%2=1 對應127.0.0.1:8001
2 2%2=0 對應127.0.0.1:8002
3 3%2=1 對應127.0.0.1:8001

6.2 接口類

在這裏插入圖片描述

6.3 Ribbon源碼

IRule接口

//IRule接口
public interface IRule{
    /*
     * choose one alive server from lb.allServers or
     * lb.upServers according to key
     * 
     * @return choosen Server object. NULL is returned if none
     *  server is available 
     */
	//選擇哪個服務實例
    public Server choose(Object key);
    
    public void setLoadBalancer(ILoadBalancer lb);
    
    public ILoadBalancer getLoadBalancer();    
}

RoundRobinRule 輪詢源碼

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() {
        nextServerCyclicCounter = new AtomicInteger(0);
    }

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

    public Server choose(ILoadBalancer lb, Object key) {
        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();

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

            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) {
    }
}

這裏用了點CAS知識點,不會的小夥伴們可以移步這裏:什麼是CAS

七. 手寫負載均衡算法

7.1 改controller

在8001項目端增加一個方法

在這裏插入圖片描述

   @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

在8002項目端同樣增加一個方法

  @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

7.2 80項目注掉@LoadBalanced

註釋掉,畢竟我們要用自己寫的
在這裏插入圖片描述

7.3 80項目增加一個接口和一個實現類

在這裏插入圖片描述
接口

package com.aiguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {

    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

實現類

package com.aiguigu.springcloud.lb;

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

import java.lang.annotation.Annotation;
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=atomicInteger.get();
            next=current>=2147483647?0:current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("***第幾次訪問,次數: "+next);
        return next;
    }


    public ServiceInstance instances(List<ServiceInstance> serviceInstances){
        int index=getAndIncrement()%serviceInstances.size();
        return serviceInstances.get(index);
    }
}

  • 這裏首先有一個原子類int型,初始值爲0,這裏用了一個自旋鎖,讓他判斷每次是不是我們之前的那個值,如果是就+1代表訪問次數又增加一次,不是就繼續循環直到判斷爲真跳出循環,這裏保證了不用synchronized方法也能在高併發下實現線程安全的增加次數
  • 第二個方法instances()實現了用當前訪問次數去%一個集羣的數量,使這個值永遠不超過集羣數量,然後得到這個值作爲獲取單個實例的下標,返回一個當前應該返回的集羣實例

7.4 controller層

新增方法getPaymentLB()

 	@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 instances1 = loadBalancer.instances(instances);
        URI uri = instances1.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }

首先獲取集羣中的實例,然後判斷是否爲空,把獲取到的list集羣傳給剛寫的方法中獲取到負載均衡獲取到的當前實例,然後獲取到實例地址,最後restTemplate去調用服務就會用到我們之前寫的負載均衡去調用

7.5 測試

調用方法會一直輪詢調用,體現了我們剛纔的負載均衡機制
在這裏插入圖片描述

在這裏插入圖片描述
服務端控制檯也打印出了第幾次訪問,服務重啓後會次數會變爲0,所以保證內存不溢出,剛纔設置的最大值爲int的最大值
在這裏插入圖片描述

終於肝完了Ribbon,說實話寫這篇的時間真的很長,因爲基礎真的很差,所以會去補一些基礎,看完可別白嫖哦~

轉載請標註!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章