SpringCloud 集成 Ribbon学习

    技术2022-07-11  70

    文章目录

    SpringCloud 集成 Ribbon学习简介Ribbon的负载均衡和Rest调用Ribbon默认自带的负载规则Ribbon负载规则替换Ribbon负载轮询算法原理RoundRobinRule源码分析Ribbon_手写轮询算法

    SpringCloud 集成 Ribbon学习

    简介

    代码地址:https://gitee.com/xueruiquan0613/cloud2020官网地址:https://github.com/Netflix/ribbon/wiki/Getting-StartedSpring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端、负载均衡工具。主要功能是提供客户端软件负载均衡算法和服务调用。Ribbon客户端提供了一系列完善的配置如连接超时,重试等。简单来说,就是配置文件中列出Load Balancer(简称LB)后面的所有的机器,Ribbon会自动帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自己的负载均衡算法。LB(负载均衡)load Balance是什么? 简单来说就是将用户的请求平坦分布到多个服务上,达到系统的HA(高可用)。 常见的负载均衡软件Nginx,LVS;硬件F5等。Ribbon本地负载均衡(进程内,即客户端负载均衡)客户端 & Nginx服务端负载均衡(集中式,即服务端负载均衡)区别: Nginx是服务端负载均衡,客户端所有请求都会交给Nginx,然后由Nginx实现转发请求,即负载均衡是由服务端实现的。 Ribbon本地负载均衡,在调用微服务接口的时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。集中式LB: 在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5;也可以是软件,如Nginx),由该设施负责将访问请求通过某种策略转发至服务的提供方。进程内LB: 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己从这些地址用选出一个合适的服务器。Ribbon就属于进程内LB,他只是一个类库,集成于消费方进程,消费方通过它来获取服务提供方的地址。

    Ribbon的负载均衡和Rest调用

    说明: Ribbon是软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和Eureka结合就是其中一个实例。 Ribbon工作时分两步:

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

    Eureka自带Ribbon依赖,所以不到如Ribbon依赖也可以实现负载均衡。

    RestTemplate 使用

    getForObject / getForEntity 方法 如果使用的是Object,返回对象为数据响应体中数据转换成的对象,基本可以理解为json 如果使用的是Entity,返回对象为ResponseEntity,包括响应中的一些重要信息,比如响应头,响应状态码,响应体等。postForObject / postForEntity 方法 // 代码模块 --- cloud-consumer-order80 @GetMapping(value = "/consumer/payment/create") public CommonResult<Payment> create(Payment payment){ log.info("OrderController create 请求参数:" + payment.toString()); return restTemplate.postForObject(PAYMENT_URL + "/payment/create",payment,CommonResult.class); } @GetMapping(value = "/consumer/payment/postForObject/create") public CommonResult<Payment> create2(Payment payment){ log.info("OrderController create postForObject 请求参数:" + payment.toString()); ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create",payment,CommonResult.class); if(entity.getStatusCode().is2xxSuccessful()){ return entity.getBody(); }else { return new CommonResult<>(444,"操作失败"); } } @GetMapping(value = "/consumer/payment/get/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id){ log.info("OrderController getPayment 请求参数:" + id); return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id,CommonResult.class); } @GetMapping(value = "/consumer/payment/getForEntity/{id}") public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){ log.info("OrderController getPayment getForEntity 请求参数:" + id); ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id,CommonResult.class); if(entity.getStatusCode().is2xxSuccessful()){ return entity.getBody(); }else { return new CommonResult<>(444, "操作失败"); } }

    Ribbon默认自带的负载规则

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

    Ribbon负载规则替换

    警告: 自定义的配置类不能放在@ComponentScan所扫描的当前包下以及子包下。 否则我们自定义的这个配置类就会被Ribbon客户端所共享,达不到特殊化定制需求。修改微服务模块 — cloud-consumer-order80 由于上述警告内容,所以配置规则需要新建不被扫描的的包。 在myrule下新建MySelfRule规则类 @Configuration public class MySelfRule { @Bean public IRule myRule(){ return new RandomRule(); // 定义为随机规则 } } 在主启动类上添加 @SpringBootApplication @EnableEurekaClient @RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class) public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args); System.out.println("OrderMain80 启动成功, 。:.゚ヽ(。◕‿◕。)ノ゚.:。+゚"); } }

    注意:增加了**@RibbonClient(name = “CLOUD-PAYMENT-SERVICE”, configuration = MySelfRule.class)**,使用自定义的负载均衡规则去调用CLOUD-PAYMENT-SERVICE下的实例。

    访问 http://localhost/consumer/payment/get/1测试 测试结果:不再是之前的轮询结果(端口号8001,8002交替出现),变成先现在的随机出现(一个端口号可能一直出现)。

    Ribbon负载轮询算法原理

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

    List serviceInstances = discoveryClient.getInstances(“CLOUD-PAYMENT-SERVICE”)

    如: List[0] serviceInstances = 127.0.0.1:8002 List[1] serviceInstances = 127.0.0.1:8001

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

    当请求数为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 当请求数为4时:4 % 2 = 0,获取的服务器地址就是127.0.0.1:8002 。。。

    RoundRobinRule源码分析

    com.netflix.loadbalancer.RoundRobinRule // 原子整型 // 高并发的情况下,i++无法保证原子性,往往会出现问题,所以引入AtomicInteger类 private AtomicInteger nextServerCyclicCounter; // 构造函数 public RoundRobinRule() { this.nextServerCyclicCounter = new AtomicInteger(0); } // 选择具体机器的源码逻辑 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) { // 获取服务可用实例列表 List<ServiceInstance>, 状态为up 、reachable List<Server> reachableServers = lb.getReachableServers(); // 获取服务实例列表 List<ServiceInstance> 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 { // 原子整型,初始为0 current = this.nextServerCyclicCounter.get(); next = (current + 1) % modulo; } while(!this.nextServerCyclicCounter.compareAndSet(current, next)); // compareAndSet --- cas,比较并交换 return next; }

    Ribbon_手写轮询算法

    修改cloud-consumer-order80微服务 ApplicationContextConfig中去掉@LoadBalanced LoadBalancer接口 public interface LoadBalancer { ServiceInstance instances(List<ServiceInstance> serviceInstances); } MyLB @Component // 注意要被Spring容器扫描 @Slf4j public class MyLB implements LoadBalancer { // 高并发的情况下,无法保证原子性,往往会出现问题,所以引入AtomicInteger类 // 初始值为0 private AtomicInteger atomicInteger = new AtomicInteger(0); // 自旋锁 public final int getAndIncrement() { int current; int next; do { current = atomicInteger.get(); // Integer.MAX_VALUE = 2147483647 next = current >= 2147483647 ? 0 : current + 1; log.info("*****第" + next + "次访问次数*****"); } while (!this.atomicInteger.compareAndSet(current, next)); return next; } @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index = getAndIncrement() % serviceInstances.size(); return serviceInstances.get(index); } } OrderController @GetMapping("/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); } 访问 http://localhost/consumer/payment/lb 测试
    Processed: 0.015, SQL: 9