zoukankan      html  css  js  c++  java
  • 09-SpringCloud Ribbon

    Ribbon入门介绍

    Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。

    简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。

    简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。

    GitHub Ribbon

    Ribbon目前也进入维护模式。

    Ribbon未来可能被Spring Cloud LoadBalacer替代。

    LB负载均衡(Load Balance)是什么

    简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高可用)。

    常见的负载均衡有软件Nginx,LVS,硬件F5等。

    Ribbon本地负载均衡客户端VS Nginx服务端负载均衡区别

    Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。即负载均衡是由服务端实现的。

    Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。

    集中式LB

    即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5, 也可以是软件,如nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方;

    进程内LB

    将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。

    Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

    一句话

    负载均衡 + RestTemplate调用

    Ribbon的负载均衡和Rest调用

    架构说明

    总结:Ribbon其实就是一个软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和Eureka结合只是其中的一个实例。

     

    Ribbon在工作时分成两步:

    • 第一步先选择EurekaServer ,它优先选择在同一个区域内负载较少的server。
    • 第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。

    其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。

    POM.xml

    先前工程项目没有引入spring-cloud-starter-ribbon也可以使用ribbon。

    测试

    1. 启动Eureka集群
    2. 启动8001和8002工程
    3. 启动80Order工程

     

    访问消费者接口测试

     http://localhost/consumer/payment/get/1

     

    已经实现本地负载轮询

    不对呀,我们并没有引入Ribbon

    因为Eureka在新版中已经默认引入了Ribbon

     

    所以不需要我们单独引入

    <dependency>
        <groupld>org.springframework.cloud</groupld>
        <artifactld>spring-cloud-starter-netflix-ribbon</artifactid>
    </dependency>

    RestTemplate的使用

    RestTemplate Java Doc

    getForObject() / getForEntity() - GET请求方法

    getForObject():返回对象为响应体中数据转化成的对象,基本上可以理解为Json。

    getForEntity():返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等

    修改80工程Controller

    @Slf4j
    @RestController
    public class OrderController {
            
          .........
      
        public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    
        @Resource
        private RestTemplate restTemplate;
    
        .........
    
        @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()) {
                return entity.getBody();//getForObject()
            } else {
                return new CommonResult<>(444, "操作失败");
            }
        }
    
    }

    postForObject() / postForEntity() - POST请求方法

    Ribbon默认自带的负载规则

    lRule:根据特定算法中从服务列表中选取一个要访问的服务

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

    Ribbon负载规则替换

    修改cloud-consumer-order80

    1. 注意配置细节
      1. 官方文档明确给出了警告:
      2. 这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。(也就是说不要将Ribbon配置类与主启动类同包)

    新建package - com.lun.myrule

    在com.dance.myrule下新建MySelfRule规则类

    package com.dance.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();
        }
    }

    主启动类添加@RibbonClient

    package com.dance.springcloud;
    
    import com.dance.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;
    
    /**
     * Hello world!
     *
     */
    @SpringBootApplication
    @EnableEurekaClient
    @RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
    public class OrderMain80
    {
        public static void main( String[] args ){
            SpringApplication.run(OrderMain80.class, args);
        }
    }

    测试

    1. 启动Eureka集群
    2. 启动提供者集群
    3. 启动消费者
    4. 浏览器测试
      1. http://localhost/consumer/payment/get/1

    测试成功,有时候是8001,有时候是8002,随机的

    Ribbon默认负载轮询算法原理

    默认负载轮训算法:

    rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务重启动后rest接口计数从1开始

    List<Servicelnstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

    如:

    • List [0] instances = 127.0.0.1:8002
    • List [1] instances = 127.0.0.1:8001

    8001+ 8002组合成为集群,它们共计2台机器,集群总数为2,按照轮询算法原理:

    • 当总请求数为1时:1%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
    • 当总请求数位2时:2%2=О对应下标位置为0,则获得服务地址为127.0.0.1:8002
    • 当总请求数位3时:3%2=1对应下标位置为1,则获得服务地址为127.0.0.1:8001
    • 当总请求数位4时:4%2=О对应下标位置为0,则获得服务地址为127.0.0.1:8002

    如此类推…

    RoundRobinRule源码分析

    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();    
    }
    package com.netflix.loadbalancer;
    
    import com.netflix.client.config.IClientConfig;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.util.List;
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
     *
     * @author stonse
     * @author Nikos Michalakis <nikos@netflix.com>
     *
     */
    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 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();
                            // 如果可达服务器或者所有服务器其中有一个为0,那么直接返回空
                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())) {
                      // 返回Server
                    return (server);
                }
    
                // Next. 将Server置空
                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 (;;) {
                  // 传入所有服务器总数量
                  // 默认为0 在初始化的时候为0
                int current = nextServerCyclicCounter.get();
                  // 当前请求数量 + 1 % 总数 获取下一个服务的下标
                int next = (current + 1) % modulo;//求余法
                  // 通过CAS设置
                if (nextServerCyclicCounter.compareAndSet(current, next))
                    return next;
            }
        }
    
        @Override
        public Server choose(Object key) {
            return choose(getLoadBalancer(), key);
        }
    
        @Override
        public void initWithNiwsConfig(IClientConfig clientConfig) {
        }
    }

    Ribbon之手写轮询算法

    自己试着写一个类似RoundRobinRule的本地负载均衡器。

    修改提供者

    • 7001/7002集群启动
    • 8001/8002微服务改造- controller , 就是都加了一个接口,返回端口号的
    @RestController
    @Slf4j
    public class PaymentController{
    
        ...
        
        @GetMapping(value = "/payment/lb")
        public String getPaymentLB() {
            return serverPort;//返回服务接口
        }
        
        ...
    }

    修改配置类

    @Configuration
    public class ApplicationContextConfig {
    
        // 应为是集群提供服务,所以需要本地负载
        @Bean
      // 去掉注解
    //    @LoadBalanced
        public RestTemplate getRestTemplate(){
            return new RestTemplate();
        }
    
    }

    修改主启动类

    @SpringBootApplication
    @EnableEurekaClient
    //@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
    public class OrderMain80
    {
        public static void main( String[] args ){
            SpringApplication.run(OrderMain80.class, args);
        }
    }

    新增负载接口

    package com.dance.springcloud.lb;
    
    import org.springframework.cloud.client.ServiceInstance;
    
    import java.util.List;
    
    /**
     * 本地负载均衡接口
     */
    public interface LoadBalancer {
        /**
         * ServiceInstance 就是 通过Discovery获取的服务实例集合
         * @param serviceInstances 服务实例
         * @return 可用的服务
         */
        ServiceInstance instances(List<ServiceInstance> serviceInstances);
    }

    新增负载实现

    package com.dance.springcloud.lb.impl;
    
    import com.dance.springcloud.lb.LoadBalancer;
    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);
    
        public final int getAndIncrement() {
            int current;
            int next;
            do {
                // 默认从 0 开始
                current = this.atomicInteger.get();
                // 如果 当前次数大于 最大的int 值直接返回 0 否则返回 当前 +1
                next = current >= 2147483647 ? 0 : current + 1;
                // 如果CAS成功
            } while (!this.atomicInteger.compareAndSet(current, next));
            System.out.println("*****第几次访问,次数next: " + next);
            // 返回下标
            return next;
        }
    
        //负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ,每次服务重启动后rest接口计数从1开始。
        @Override
        public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
            // 下标 % 服务实例数量
            int index = getAndIncrement() % serviceInstances.size();
            // 返回实例
            return serviceInstances.get(index);
        }
    }

    修改Controller

    package com.dance.springcloud.controller;
    
    import com.dance.springcloud.entities.CommonResult;
    import com.dance.springcloud.entities.Payment;
    import com.dance.springcloud.lb.LoadBalancer;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.discovery.DiscoveryClient;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.client.RestTemplate;
    
    import javax.annotation.Resource;
    import java.net.URI;
    import java.util.List;
    
    @Slf4j
    @RestController
    public class OrderController {
    
        //public static final String PAYMENT_URL = "http://localhost:8001";
    // 将指定的地址修改为服务别名 服务别名从Eureka控制台查看
        public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    
        @Resource
        private RestTemplate restTemplate;
    
        @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 serviceInstance = loadBalancer.instances(instances);
            URI uri = serviceInstance.getUri();
            return restTemplate.getForObject(uri + "/payment/lb", String.class);
        }
    
    
    }

    测试

     

    测试成功~ 完结撒花

    作者:彼岸舞

    时间:2021822

    内容关于:Spring Cloud H版

    本文属于作者原创,未经允许,禁止转发

  • 相关阅读:
    atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy
    atitit.查看预编译sql问号 本质and原理and查看原生sql语句
    atitit.基于http json api 接口设计 最佳实践 总结o7
    atitit.spring3 mvc url配置最佳实践
    Atitit.列表页面and条件查询的实现最佳实践(2)翻页 分页 控件的实现java .net php
    atitit。自定义uml MOF EMF体系eclipse emf 教程o7t
    atitit.编辑表单的实现最佳实践dwr jq easyui
    Atitit. 提升开发效率与质量DSL ( 3) 实现DSL的方式总结
    atitit.设计模式(2) 查表模式/ command 总结
    Atitit. 提升软件开发效率and 开发质量java 实现dsl 4gl 的本质and 精髓 O725
  • 原文地址:https://www.cnblogs.com/flower-dance/p/15172969.html
Copyright © 2011-2022 走看看