聊聊SpringCloud中的Ribbon進行服務調用的問題

前置內容
(1)、微服務理論入門和手把手帶你進行微服務環境搭建及支付、訂單業務編寫
(2)、SpringCloud之Eureka服務註冊與發現
(3)、SpringCloud之Zookeeper進行服務註冊與發現
(4)、SpringCloud之Consul進行服務註冊與發現

1、Robbon

1.1、Ribbon概述

(1)、Ribbon是什麼?

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

(2)、Ribbon的官網

官網地址

且目前也進入瞭維護模式

(3)、負載均衡(LB)

  • 負載均衡就是將用戶的請求平攤的分配到多個服務上,從而達到系統的HA(高可用)。常見的負載均衡由軟件nginxLVSF5

1.集中式LB:就是在服務的消費方和提供方之間使用獨立的LB設施(可以是硬件,如F5,也可以是軟件,如nginx),由該設施負責把訪問請求通過某種策略轉發至服務的提供方。

2.進程內LB:將LB邏輯集成到消費方,消費方從服務註冊中心獲知有哪些地址可用,然後自己再從這些地址中選擇出一個合適的服務器。Ribbon就屬於進程內LB,它隻是一個類庫,集成於消費方進程,消費方通過它來獲取服務提供方的地址。

(4)、Ribbon本地負載均衡客戶端和Nginx服務端負載均衡的區別

  1. Nginx是服務器負載均衡,客戶端所有請求都會交給nginx實現轉發請求。即負載均衡是由服務端實現的。
  2. Ribbon本地負載均衡,在調用微服務接口的時候,會在註冊中心獲取註冊信息列表之後緩存到JVM本地,從而在本地實現RPC遠程服務調用技術。

1.2、Ribbon負載均衡演示

(1)、架構說明

Ribbon其實就是一個軟負載均衡的客戶端組件,他可以和其他所需請求的客戶端結合使用,和eureka結合隻是其中的一個實例。

在這裡插入圖片描述

Ribbon在工作時分為兩步

  • 第一步先選擇EurekaServer,他優先選擇在同一個區域內負載較少的server
  • 第二步再根據用戶指定的策略,在從server取到的服務註冊列表中選擇一個地址。其中Ribbon提供瞭多種策略:比如輪詢、隨機和根據響應時間加權。

(2)、POM文件

在這裡插入圖片描述

所以在引入Eureka的整合包中就包含瞭整合Ribbonjar包。

所以我們前面實現的8001和8002交替訪問的方式就是所謂的負載均衡。

(3)、RestTemplate的說明

getForObject:返回對象為響應體中數據轉化成的對象,基本上可以理解為Json。getForEntity:返回對象為ResponseEntity對象,包含瞭響應中的一些重要信息,比如響應頭、響應狀態碼、響應體等。postForObjectpostForEntity

1.3、Ribbon核心組件IRule

在這裡插入圖片描述

1. 主要的負載規則

  • RoundRobinRule:輪詢
  • RandomRule:隨機
  • RetryRule:先按照RoundRobinRule的策略獲取服務,如果獲取服務失敗則在指定時間內會進行重試
  • WeightedResponseTimeRule:對RoundRobinRule的擴展,響應速度越快的實例選擇權重越大,越容易被選擇
  • BestAvailableRule:會先過濾掉由於多次訪問故障而處於斷路器跳閘狀態的服務,然後選擇一個並發量最小的服務
  • AvailabilityFilteringRule:先過濾掉故障實例,再選擇並發較小的實例
  • ZoneAvoidanceRule:默認規則,復合判斷server所在區域的性能和server的可用性選擇服務器

2. 如何替換負載規則

  • cloud-consumer-order80包下的配置進行修改。
  • 我們自己自定義的配置類不能放在@ComponentScan所掃描的當前包以及子包下,否則我們自定義的這個配置類就會被所有的Ribbon客戶端所共享,達不到特殊化定制的目的瞭。
  • com.xiao的包下新建一個myrule的子包。

在這裡插入圖片描述

  1. myrule的包下新建一個MySelfRule配置類
​​​​​​​
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 getRandomRule(){
        return new RandomRule(); // 新建隨機訪問負載規則
    }
}
  1. 對主啟動類進行修改,修改為如下:
import com.xiao.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.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);
    }
}

6.測試結果 結果就是以我們最新配置的隨機方式進行訪問的。

1.4、Ribbon負載均衡算法

1.4.1、輪詢算法原理 負載均衡算法:

rest接口第幾次請求數 % 服務器集群總數量 = 實際調用服務器位置下標,每次服務重新啟動後rest接口計數從1開始。

在這裡插入圖片描述

1.4.2、RoundRobinRule 源碼

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) {
                	// 獲取狀態為up的服務提供者
                    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;
            // CAS判斷,如果判斷成功就返回true,否則就一直自旋
        } while(!this.nextServerCyclicCounter.compareAndSet(current, next));

        return next;
    }
}

1.4.3、手寫輪詢算法

1. 修改支付模塊的Controller

添加以下內容

@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
      return ServerPort;
}

2. ApplicationContextConfig去掉@LoadBalanced註解

3. LoadBalancer接口

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {
    //收集服務器總共有多少臺能夠提供服務的機器,並放到list裡面
    ServiceInstance instances(List<ServiceInstance> serviceInstances);

}

4. 編寫MyLB類

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

5. 修改OrderController類

import com.xiao.cloud.entities.CommonResult;
import com.xiao.cloud.entities.Payment;
import com.xiao.cloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

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

6. 測試結果

  • 最後是在80018002兩個之間進行輪詢訪問。
  • 控制臺輸出如下

在這裡插入圖片描述

7. 包結構示意圖

在這裡插入圖片描述

到此這篇關於SpringCloud中的Ribbon進行服務調用的文章就介紹到這瞭,更多相關SpringCloud Ribbon服務調用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: