欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

聊聊SpringCloud中的Ribbon進(jìn)行服務(wù)調(diào)用的問題

 更新時間:2022年01月10日 16:39:30   作者:崇尚學(xué)技術(shù)的科班人  
SpringCloud-Ribbon是基于Netflix?Ribbon實現(xiàn)的一套客戶端負(fù)載均衡的工具。本文給大家介紹SpringCloud中的Ribbon進(jìn)行服務(wù)調(diào)用的問題,感興趣的朋友跟隨小編一起看看吧

前置內(nèi)容
(1)、微服務(wù)理論入門和手把手帶你進(jìn)行微服務(wù)環(huán)境搭建及支付、訂單業(yè)務(wù)編寫
(2)、SpringCloud之Eureka服務(wù)注冊與發(fā)現(xiàn)
(3)、SpringCloud之Zookeeper進(jìn)行服務(wù)注冊與發(fā)現(xiàn)
(4)、SpringCloud之Consul進(jìn)行服務(wù)注冊與發(fā)現(xiàn)

1、Robbon

1.1、Ribbon概述

(1)、Ribbon是什么?

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

(2)、Ribbon的官網(wǎng)

官網(wǎng)地址

且目前也進(jìn)入了維護(hù)模式

(3)、負(fù)載均衡(LB)

  • 負(fù)載均衡就是將用戶的請求平攤的分配到多個服務(wù)上,從而達(dá)到系統(tǒng)的HA(高可用)。常見的負(fù)載均衡由軟件nginx、LVS、F5

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

2.進(jìn)程內(nèi)LB:將LB邏輯集成到消費方,消費方從服務(wù)注冊中心獲知有哪些地址可用,然后自己再從這些地址中選擇出一個合適的服務(wù)器。Ribbon就屬于進(jìn)程內(nèi)LB,它只是一個類庫,集成于消費方進(jìn)程,消費方通過它來獲取服務(wù)提供方的地址。

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

  1. Nginx是服務(wù)器負(fù)載均衡,客戶端所有請求都會交給nginx實現(xiàn)轉(zhuǎn)發(fā)請求。即負(fù)載均衡是由服務(wù)端實現(xiàn)的。
  2. Ribbon本地負(fù)載均衡,在調(diào)用微服務(wù)接口的時候,會在注冊中心獲取注冊信息列表之后緩存到JVM本地,從而在本地實現(xiàn)RPC遠(yuǎn)程服務(wù)調(diào)用技術(shù)。

1.2、Ribbon負(fù)載均衡演示

(1)、架構(gòu)說明

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

在這里插入圖片描述

Ribbon在工作時分為兩步

  • 第一步先選擇EurekaServer,他優(yōu)先選擇在同一個區(qū)域內(nèi)負(fù)載較少的server
  • 第二步再根據(jù)用戶指定的策略,在從server取到的服務(wù)注冊列表中選擇一個地址。其中Ribbon提供了多種策略:比如輪詢、隨機和根據(jù)響應(yīng)時間加權(quán)。

(2)、POM文件

在這里插入圖片描述

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

所以我們前面實現(xiàn)的8001和8002交替訪問的方式就是所謂的負(fù)載均衡。

(3)、RestTemplate的說明

getForObject:返回對象為響應(yīng)體中數(shù)據(jù)轉(zhuǎn)化成的對象,基本上可以理解為Json。getForEntity:返回對象為ResponseEntity對象,包含了響應(yīng)中的一些重要信息,比如響應(yīng)頭、響應(yīng)狀態(tài)碼、響應(yīng)體等。postForObjectpostForEntity

1.3、Ribbon核心組件IRule

在這里插入圖片描述

1. 主要的負(fù)載規(guī)則

  • RoundRobinRule:輪詢
  • RandomRule:隨機
  • RetryRule:先按照RoundRobinRule的策略獲取服務(wù),如果獲取服務(wù)失敗則在指定時間內(nèi)會進(jìn)行重試
  • WeightedResponseTimeRule:對RoundRobinRule的擴(kuò)展,響應(yīng)速度越快的實例選擇權(quán)重越大,越容易被選擇
  • BestAvailableRule:會先過濾掉由于多次訪問故障而處于斷路器跳閘狀態(tài)的服務(wù),然后選擇一個并發(fā)量最小的服務(wù)
  • AvailabilityFilteringRule:先過濾掉故障實例,再選擇并發(fā)較小的實例
  • ZoneAvoidanceRule:默認(rèn)規(guī)則,復(fù)合判斷server所在區(qū)域的性能和server的可用性選擇服務(wù)器

2. 如何替換負(fù)載規(guī)則

  • cloud-consumer-order80包下的配置進(jìn)行修改。
  • 我們自己自定義的配置類不能放在@ComponentScan所掃描的當(dāng)前包以及子包下,否則我們自定義的這個配置類就會被所有的Ribbon客戶端所共享,達(dá)不到特殊化定制的目的了。
  • 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(); // 新建隨機訪問負(fù)載規(guī)則
    }
}
  1. 對主啟動類進(jìn)行修改,修改為如下:
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.測試結(jié)果 結(jié)果就是以我們最新配置的隨機方式進(jìn)行訪問的。

1.4、Ribbon負(fù)載均衡算法

1.4.1、輪詢算法原理 負(fù)載均衡算法:

rest接口第幾次請求數(shù) % 服務(wù)器集群總數(shù)量 = 實際調(diào)用服務(wù)器位置下標(biāo),每次服務(wù)重新啟動后rest接口計數(shù)從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) {
                	// 獲取狀態(tài)為up的服務(wù)提供者
                    List<Server> reachableServers = lb.getReachableServers();
                    // 獲取所有的服務(wù)提供者
                    List<Server> allServers = lb.getAllServers();
                    int upCount = reachableServers.size();
                    int serverCount = allServers.size();
                    
                    if (upCount != 0 && serverCount != 0) {
                    	// 對取模獲得的下標(biāo)進(jìn)行獲取相關(guān)的服務(wù)提供者
                        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

添加以下內(nèi)容

@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 {
    //收集服務(wù)器總共有多少臺能夠提供服務(wù)的機器,并放到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);

    //坐標(biāo)
    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));  //第一個參數(shù)是期望值,第二個參數(shù)是修改值是
        System.out.println("*******第幾次訪問,次數(shù)next: "+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {  //得到機器的列表
        int index = getAndIncrement() % serviceInstances.size(); //得到服務(wù)器的下標(biāo)位置
        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. 測試結(jié)果

  • 最后是在80018002兩個之間進(jìn)行輪詢訪問。
  • 控制臺輸出如下

在這里插入圖片描述

7. 包結(jié)構(gòu)示意圖

在這里插入圖片描述

到此這篇關(guān)于SpringCloud中的Ribbon進(jìn)行服務(wù)調(diào)用的文章就介紹到這了,更多相關(guān)SpringCloud Ribbon服務(wù)調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 深入理解Java對象復(fù)制

    深入理解Java對象復(fù)制

    使用任何已有的工具,都沒有直接使用 get set 方式進(jìn)行,對象轉(zhuǎn)換的速度快,雖然get set 方式代碼對一些比較麻煩,但是效率要高一些的,推薦使用 MapStruct 方式.,需要的朋友可以參考下
    2021-05-05
  • Java中使用MongoDB數(shù)據(jù)庫實例Demo

    Java中使用MongoDB數(shù)據(jù)庫實例Demo

    MongoDB是由C++語言編寫的,基于分布式文件存儲的數(shù)據(jù)庫,是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是最接近于關(guān)系型數(shù)據(jù)庫的NoSQL數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關(guān)于Java中使用MongoDB數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下
    2023-12-12
  • 排序算法圖解之Java插入排序

    排序算法圖解之Java插入排序

    插入排序是一種最簡單的排序方法,它的基本思想是將一個記錄插入到已經(jīng)排好序的有序表中,從而一個新的、記錄數(shù)增1的有序表。本文通過圖片合示例講解了插入排序的實現(xiàn),需要的可以了解一下
    2022-11-11
  • IDEA2021.2永久激活碼最新超詳細(xì)(激活到2099)

    IDEA2021.2永久激活碼最新超詳細(xì)(激活到2099)

    這篇文章主要介紹了IDEA2021.2永久激活碼,是idea2021版最新激活方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Spring Security 實現(xiàn)“記住我”功能及原理解析

    Spring Security 實現(xiàn)“記住我”功能及原理解析

    這篇文章主要介紹了Spring Security 實現(xiàn)“記住我”功能及原理解析,需要的朋友可以參考下
    2020-05-05
  • js實現(xiàn)拖拽拼圖游戲

    js實現(xiàn)拖拽拼圖游戲

    這篇文章主要為大家詳細(xì)介紹了js實現(xiàn)拖拽拼圖游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Java?Chassis3熔斷機制的改進(jìn)路程技術(shù)解密

    Java?Chassis3熔斷機制的改進(jìn)路程技術(shù)解密

    這篇文章主要介紹了Java?Chassis?3技術(shù)解密之熔斷機制的改進(jìn)路程實例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • 使用maven命令安裝jar包到本地倉庫的方法步驟

    使用maven命令安裝jar包到本地倉庫的方法步驟

    這篇文章主要介紹了使用maven命令安裝jar包到本地倉庫的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • jackson使用@JsonSerialize格式化BigDecimal解決.00不顯示問題

    jackson使用@JsonSerialize格式化BigDecimal解決.00不顯示問題

    這篇文章主要介紹了jackson使用@JsonSerialize格式化BigDecimal解決.00不顯示問題,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下
    2015-02-02
  • springboot 傳參校驗@Valid及對其的異常捕獲方式

    springboot 傳參校驗@Valid及對其的異常捕獲方式

    這篇文章主要介紹了springboot 傳參校驗@Valid及對其的異常捕獲方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10

最新評論