聊聊SpringCloud中的Ribbon进行服务调用的问题

2023-01-21 0 1,018

目录

前置内容
(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结合只是其中的一个实例。

聊聊SpringCloud中的Ribbon进行服务调用的问题

Ribbon在工作时分为两步

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

(2)、POM文件

聊聊SpringCloud中的Ribbon进行服务调用的问题

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

所以我们前面实现的8001和8002交替访问的方式就是所谓的负载均衡。

(3)、RestTemplate的说明

getForObject:返回对象为响应体中数据转化成的对象,基本上可以理解为Json。getForEntity:返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等。postForObjectpostForEntity

1.3、Ribbon核心组件IRule

聊聊SpringCloud中的Ribbon进行服务调用的问题

1. 主要的负载规则

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

2. 如何替换负载规则

  • cloud-consumer-order80包下的配置进行修改。
  • 我们自己自定义的配置类不能放在@ComponentScan所扫描的当前包以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。
  • com.xiao的包下新建一个myrule的子包。

聊聊SpringCloud中的Ribbon进行服务调用的问题

  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开始。

聊聊SpringCloud中的Ribbon进行服务调用的问题

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两个之间进行轮询访问。
  • 控制台输出如下

聊聊SpringCloud中的Ribbon进行服务调用的问题

7. 包结构示意图

聊聊SpringCloud中的Ribbon进行服务调用的问题

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 聊聊SpringCloud中的Ribbon进行服务调用的问题 http://www.20zxx.cn/463419/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务