【6】Ribbon:负载均衡(基于客户端)

一、ribbon是什么?

  • Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具
  • 简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将NetFlix的中间层服务连接在一起。Ribbon的客户端组件提供一系列完整的配置项如:连接超时、重试等等。简单的说,就是在配置文件中列出LoadBalancer (简称LB:负载均衡)后面所有的机器,Ribbon会 自动的帮助你基于某种规则(如简单轮询,随机连接等等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法!

二、ribbon能干嘛?

  • LB,即负载均衡(Load Balance),在微服务或分布式集群中经常用的一种应用。
  • 负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高可用)
  • 常见的负载均衡软件有Nginx, Lvs 等等
  • dubbo、SpringCloud中均给我们提供了负载均衡,SpringCloud的负载均衡算法可以自定义
  • 负载均衡简单分类:
    • 集中式LB
      • 即在服务的消费方和提供方之间使用独立的LB设施,如Nginx, 由该设施负责把访问请求通过某种策略转发至服务的提供方!
        进程式LB
    • 进程式LB
      • 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选出一个合适的服务器。
      • Ribbon就属于进程内LB,它只是一个类库, 集成于消费方进程,消费方通过它来获取到服务提供方的地址!

三、继承Ribbon

在Springcloud-consumer-dept-80中添加maven依赖

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

application.yml文件中配置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/

在启动类上加@EnableEurekaClient注解:

@SpringBootApplication
@EnableEurekaClient  //开启Eureka 客户端
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

自定义Spring配置类:ConfigBean.java 配置负载均衡实现RestTemplate

@Configuration
public class ConfigBean { //@Configuration 注解相当于在spring中的applicationContext.xml

    //配置负载均衡实现RestTemplate
    @Bean
    @LoadBalanced//Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
    
}

修改Controller:将原先固定的访问地址改为一个变量,现在eureka注册中心有三个,随便访问那个都能得到服务地址,现在通过服务名来访问。

//    private static final String REST_URL_PREFIX="http://localhost:8001";
    //这里的地址应该是一个变量,通过服务名来访问
    private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT";

四、实现负载均衡

实现目标:发发发发发发
1.新建两个服务提供者Moudle:springcloud-provider-dept-8002、springcloud-provider-dept-8003
2.参照springcloud-provider-dept-8001 依次为另外两个Moudle添加pom.xml依赖 、resourece下的mybatis和application.yml配置,Java代码
其中application.yml内容为:

server:
  port: 8002

#mybatis配置
mybatis:
  type-aliases-package: com.fusheng.springcloud.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml
  config-location: classpath:mybatis/mybatis-config.xml  #mybatis核心配置文件,可以不写
#  configuration: #把数据库的写法写成驼峰命令发
#    map-underscore-to-camel-case: true

#spring配置
spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #数据源
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/springcloud_db02?useSSL=false&useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456

#eureka的配置,服务注册到那里
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept8002 #修改eureka上的默认描述信息


#info
info:
  app.name: fusheng-springcloud
  company.name: fusheng.com

3.启动服务(看自己电脑配置启动服务个数),访问http://eureka7001.com:7001/ 查看服务在这里插入图片描述
现在服务已经有三个服务,现在启动DeptConsumer_80服务,测试访问http://localhost/consumer/dept/list ,多刷新几次发现此时的负载均衡策略是轮询
在这里插入图片描述

五、自定义轮询规则

在springcloud-provider-dept-80模块下的ConfigBean中进行配置,切换使用不同的规则

@Configuration
public class ConfigBean {
    //@Configuration -- spring  applicationContext.xml
    /**
     * IRule:
     * RoundRobinRule 轮询策略
     * RandomRule 随机策略
     * AvailabilityFilteringRule : 会先过滤掉,跳闸,访问故障的服务~,对剩下的进行轮询~
     * RetryRule : 会先按照轮询获取服务~,如果服务获取失败,则会在指定的时间内进行,重试
     */
//配置负载均衡实现RestTemplate
    @Bean
    @LoadBalanced//Ribbon
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
    @Bean
    public IRule myRule() {
        return new RandomRule();//使用随机策略
        //return new RoundRobinRule();//使用轮询策略
        //return new AvailabilityFilteringRule();//使用轮询策略
        //return new RetryRule();//使用轮询策略
    }
}

也可以自定义自己的策略,在myRule包下自定义一个配置类MyRule.java,注意:该包不要和主启动类所在的包同级,要跟启动类所在包同级:在这里插入图片描述

@Configuration
public class FushengRule {
    @Bean
    public IRule myRule() {
        return new MyRandomRule();//默认是轮询RandomRule,现在自定义为自己的
    }
}

自定义的规则 MyRandomRule类内容:


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 MyRandomRule extends AbstractLoadBalancerRule {


    /**
     * 每个服务访问5次则换下一个服务(总共3个服务)
     * 
     * total=0,默认=0,如果=5,指向下一个服务节点
     * index=0,默认=0,如果total=5,index+1
     */
    private int total = 0;//被调用的次数
    private int currentIndex = 0;//当前是谁在提供服务


    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            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 = this.chooseRandomInt(serverCount);  //生产区间随机数
//                server = (Server)upList.get(index); //从活着的服务中随机获取一个

                //=====================自定义代码=========================
                if (total < 5) {
                    server = upList.get(currentIndex);
                    total++;
                } else {
                    total = 0;
                    currentIndex++;
                    if (currentIndex > upList.size()) {
                        currentIndex = 0;
                    }
                    server = upList.get(currentIndex);//从活着的服务中,获取指定的服务来进行操作
                }
                //======================================================

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

主启动类开启负载均衡并指定自定义的MyRule配置类:

@SpringBootApplication
//Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号
@EnableEurekaClient  //开启Eureka 客户端
//在微服务启动的时候就能去加载我们自己定义Ribbon类
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = FushengRule.class)
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

在url http://localhost/consumer/dept/list 中基于自己的规则每个服务都会提供5次再切换下一个服务。注意:这里多次刷新后服务会蹦!在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值