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

    SpringCloud ---- Ribbon

    1. Ribbon概述

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

    • 负载均衡LB (Load Balance),简单的来说就是将用户的请求平摊的分配到多个服务上, 从而达到系统的HA(高可用)

    • 负载均衡的分类

      1. 集中式负载均衡,客户端和服务端使用独立的负载均衡措施(硬件的F5,软件的Nginx)

      1149971-20190617115318385-271620277

      1. 进程内负载均衡,将负载均衡逻辑集成在客户端组件中,客户端从注册中心获取可用服务,然后再从服务地址中选择合适的服务端发起请求(Ribbon

    1149971-20190617115552199-963109768

    • Ribbon要从注册中心获取可用的服务, 同时是集成在客户端, 因此, 我们要在consumer中进行操作, 依赖要包括ribbon和eureka

    2. 使用Ribbon实现负载均衡

    由于Ribbon是在客户端进行负载均衡的操作, 因此我们只需要操作consumer服务就行了

    1. 导入依赖

    <!--Ribbon-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--Eureka-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    

    注意

    • Ribbon要去Eureka中发现可用的服务, 因此除了引入Ribbon依赖以外, 也要引入Eureka的依赖

    2. 配置Config

    package com.wang.springcloud.config;
    
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    @Configuration
    public class ConfigBean {
    
        //配置负载均衡实现RestTemplate
        @LoadBalanced   //Ribbon
        //注册RestTemplate
        @Bean
        public RestTemplate getRestTemplate() {
            return new RestTemplate();
        }
    
    }
    

    注意

    • Ribbon利用RestTemplate的URL实现负载均衡, 因此要在注册RestTemplate时开启Ribbon对RestTemplate的负载均衡的支持, 这里加一个 @LoadBalanced 注解就可以了

    3. 改写controller

    package com.wang.springcloud.controller;
    
    import com.wang.springcloud.pojo.Dept;
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.List;
    
    @ApiModel("Consumer Controller")
    @RestController
    public class DeptConsumerController {
        //消费者, 不应该有service层!(为了实现解耦)
        //RestFul模板 ==> RestTemplate, 里面有很多方法供我们直接调用, 需要注册到Spring中
        //远程调用provider的url
    
        //在ConfigBean中注册了, 这里可以直接自动装配(AutoWired是按照类型自动装配)
        //RestTemplate的方法 ==> url, 请求的实体(request), 响应的类型(response)Class<T>
        //RestTemplate实质上就是提供多种便捷访问远程http服务的方法, 是一个简单的RestFul服务模板
        @Autowired
        private RestTemplate restTemplate;
    
        //通过Ribbon, 我们这里的地址应该是一个变量, 不要写死, 通过服务名来访问(provider的spring.applicatoion.name的大写), 不要忘了写http://
        private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
        @ApiOperation("通过部门编号查询一个部门")
        @RequestMapping(value = "/consumer/dept/get/{id}", method = RequestMethod.GET)
        public Dept get(@PathVariable("id") @ApiParam("部门编号") Long id) {
            //由于我们在provider中的list是get方法, 这里调用getForObject方法
            return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
        }
    
        @ApiOperation("通过部门名称添加一个部门")
        @RequestMapping(value = "/consumer/dept/add", method = RequestMethod.POST)
        public boolean add(@ApiParam("部门的名称") Dept dept){
            return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
        }
    
        @ApiOperation("查询全部的部门")
        @RequestMapping(value = "consumer/dept/list", method = RequestMethod.GET)
        public List<Dept> list() {
            return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
        }
    }
    

    注意

    • 这里的核心代码是

      private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
      

      通过服务名来访问provider

    • 由于是通过服务名来访问provider, 因此做provider的被发现的服务要有相同的 spring.applicatoion.name

    • 这里本质上还是url, 不要忘了写 http://

    4. 配置application

    server:
      port: 8080
    
    #Eureka配置
    eureka:
      client:
        register-with-eureka: false #我们这里是消费者, 是客户端, 因此不需要想Eureka中注册自己
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    

    注意

    • 这里由于用到了Eureka进行服务的注册与发现, 要配置Eureka
    • 我们这里是消费者, 是客户端, 因此不需要想Eureka中注册自己, 要配置 register-with-eureka: false

    5. 配置主启动类

    package com.wang.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    //Ribbon 和 Eureka 整合以后, 客户端可以直接调用, 不用关心IP地址和端口号
    @SpringBootApplication
    @EnableEurekaClient
    public class DeptConsumer_8080 {
        public static void main(String[] args) {
            SpringApplication.run(DeptConsumer_8080.class, args);
        }
    }
    

    注意

    • 添加 @EnableEurekaClient 注解, 表明他是一个Eureka的客户端, 可以使用Eureka进行服务的发现

    6. 添加服务的提供者

    这里添加了三个服务的提供者, 端口分别为8001, 8002, 8003

    image-20201012095135025

    注意

    • 三个服务的提供者内容基本相同, 因为要做负载均衡

    • 注意要修改application的配置, 主要是端口号

    • 由于Ribbon是通过服务的名称进行发现并负载均衡的, 注意这里的Spring的名字要相同, 即

      #Spring的配置
      spring:
        application:
          name: springcloud-provider-dept   #三个服务名称一致是前提!
      
    • 这里以第三个数据库为例, 给出建库的sql代码

      create database /*!32312 IF NOT EXISTS*/`db03` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
      use `db03`;
      /*Table structure for table `dept` */
      
      drop table if exists `dept`;
      
      create table `dept` (
        `deptno` bigint(20) not null auto_increment,
        `dname` varchar(60) default null,
        `db_source` varchar(60) default null,
        primary key (`deptno`)
      ) engine=innodb auto_increment=1 default charset=utf8mb4 comment='部门表';
      
      /*Data for the table `dept` */
      
      insert into dept (dname, db_source) values ('开发部', database());
      insert into dept (dname, db_source) values ('人事部', database());
      insert into dept (dname, db_source) values ('财务部', database());
      insert into dept (dname, db_source) values ('市场部', database());
      insert into dept (dname, db_source) values ('运维部', database());
      

    3. 自定义负载均衡算法

    1. Ribbon的一些自定义策略

    • Ribbon的策略实现的接口时IRule
    • 一些策略
      • AvailabilityFilteringRule 会先过滤掉跳闸或者访问故障的服务
      • RoundRobinRule 轮询, 默认的
      • RandomRule 随机
      • RetryRule 会先按照轮询获取服务, 如果服务获取失败, 则会在指定的时间内进行重试

    2. 使用随机策略

    @Bean
    public IRule myRule() {
        return new RandomRule();
    }
    

    注意

    • Ribbon默认的策略为轮询算法
    • 想要更改为Ribbon内置的其他算法, 只需要将其内置的策略注册进Bean就好了
    • 类型为IRule, 返回值为想要用的内置的策略

    3. 自定义策略

    1. 建立自定义策略类

    image-20201012102309090

    注意

    • 自定义策略选择不要与主启动类同级, 否则会被主启动类扫描到, 这样所有的服务都使用了同样的策略

    2. 配置主启动类

    package com.wang.springcloud;
    
    import com.wang.myRule.WangRule;
    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;
    
    //Ribbon 和 Eureka 整合以后, 客户端可以直接调用, 不用关心IP地址和端口号
    @SpringBootApplication
    @EnableEurekaClient
    //在微服务启动的时候, 就可以去加载我们自定义的Ribbon类
    @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT", configuration = WangRule.class)
    public class DeptConsumer_8080 {
        public static void main(String[] args) {
            SpringApplication.run(DeptConsumer_8080.class, args);
        }
    }
    

    注意

    • 这里添加了 @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT", configuration = WangRule.class) 注解, 指定了服务的名称. 同时, 由于我们自定义的策略与SpringBoot的主启动类不在一级, 不会被扫描到, 这里需要指定策略的类

    3. 编写自己的策略

    package com.wang.myRule;
    
    import com.netflix.client.config.IClientConfig;
    import com.netflix.loadbalancer.AbstractLoadBalancerRule;
    import com.netflix.loadbalancer.ILoadBalancer;
    import com.netflix.loadbalancer.Server;
    
    import java.util.List;
    import java.util.concurrent.ThreadLocalRandom;
    
    public class WangRandomRule extends AbstractLoadBalancerRule {
    
        /**
         * 每个服务访问5次, 换下一个服务
         *
         * total=0, 默认=0, 如果=5, 我们指向下一个服务节点
         * index=0, 默认0, 如果total=5, index+1
         */
    //    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
    
        private int total = 0;      //总共被调用的次数
    
        private int currentIndex = 0;   //当前是谁在提供服务
    
        public Server choose(ILoadBalancer lb, Object key) {
            if (lb == null) {
                return null;
            }
            Server server = null;
    
            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
    
                //获得活着的服务
                List<Server> upList = lb.getReachableServers();
                //获得全部的服务
                List<Server> allList = lb.getAllServers();
    
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
    
    //            //生成区间随机数
    //            int index = chooseRandomInt(serverCount);
    //            //从活着的服务中随机获取一个
    //            server = upList.get(index);
    
                //-============================================
    
                if (total < 5) {
                    server = upList.get(currentIndex);
                    total++;
                } else {
                    total = 0;
                    currentIndex++;
                    //index从0开始, list的大小要-1, 这里用 >=
                    if (currentIndex >= upList.size()) {
                        currentIndex = 0;
                    }
                    //从活着的服务中, 获取指定的服务来进行操作
                    server = upList.get(currentIndex);
                }
    
    
                //-============================================
    
                if (server == null) {
                    Thread.yield();
                    continue;
                }
    
                if (server.isAlive()) {
                    return (server);
                }
    
                server = null;
                Thread.yield();
            }
    
            return server;
    
        }
    
        protected int chooseRandomInt(int serverCount) {
            return ThreadLocalRandom.current().nextInt(serverCount);
        }
    
        @Override
        public Server choose(Object key) {
            return choose(getLoadBalancer(), key);
        }
    
        @Override
        public void initWithNiwsConfig(IClientConfig clientConfig) {
            // TODO Auto-generated method stub
    
        }
    }
    

    4. 注册自定义策略

    package com.wang.myRule;
    
    import com.netflix.loadbalancer.IRule;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class WangRule {
    
        @Bean
        public IRule myRule() {
            return new WangRandomRule();
        }
    
    }
    
  • 相关阅读:
    android常用组件
    android button点击效果
    service+activity
    收藏
    c++
    工厂模式
    lr常遇到一些问题
    lr介绍
    ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL)' at line 1"))
    mysqlclient 1.4.0 or newer is required; you have 0.10.0
  • 原文地址:https://www.cnblogs.com/wang-sky/p/13801474.html
Copyright © 2011-2022 走看看