[JAVA] SpringCloud Netflix Ribbon超详细讲解

2123 0
黑夜隐士 2022-11-8 17:13:42 | 显示全部楼层 |阅读模式
目录

    一、Ribbon简介
      1、什么是Ribbon2、Ribbon能干什么
    二、使用Ribbon
      1、客户端导入依赖2、application.yml配置3、Controller配置4、Config的配置5、启动类的配置
    三、Ribbon实现负载均衡四、设计负载均衡算法
      1、80启动类的改动2、自定义路由类3、负载均衡算法的实现



一、Ribbon简介


1、什么是Ribbon

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

2、Ribbon能干什么



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

二、使用Ribbon


1、客户端导入依赖
  1.      <!--引入Eureka的依赖-->
  2.      <dependencies>
  3.         <dependency>
  4.             <groupId>org.springframework.cloud</groupId>
  5.             <artifactId>spring-cloud-starter-eureka</artifactId>
  6.             <version>1.4.6.RELEASE</version>
  7.         </dependency>
  8.         <!--引入ribbon-->
  9.         <dependency>
  10.             <groupId>org.springframework.cloud</groupId>
  11.             <artifactId>spring-cloud-starter-ribbon</artifactId>
  12.             <version>1.4.6.RELEASE</version>
  13.         </dependency>
  14.     </dependencies>
复制代码
2、application.yml配置

server:
  port: 801
eureka:
  client:
    register-with-eureka: false  #不向eureka注册自己
    service-url:
      defaultZone: http://localhost:7001/eureka/ #去哪个地方获取

3、Controller配置

和前面两节不一样的是,用Ribbon做负载均衡,地址不能写死,也就是不能和前面的一样写成一个具体的值如:localhost:8001,而是这个微服务的名字,也就是这个名字,如下。

  1. package com.you.controller;
  2. import com.you.pojo.Dept;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.client.RestTemplate;
  7. import java.util.List;
  8. @RestController
  9. @ResponseBody
  10. public class DeptComsumerController {
  11.     @Autowired
  12.     RestTemplate restTemplate;
  13. //    public static final String REST_URL_PREFIX = "http://localhost:8001";
  14.     public static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
  15.     @GetMapping("/consumer/dept/getDept/{id}")
  16.     public Dept getDeptOfId(@PathVariable("id") Long id)
  17.     {
  18.         System.out.println(REST_URL_PREFIX+"/dept"+"/aDept/"+id);
  19.         return restTemplate.getForObject(REST_URL_PREFIX + "/dept" + "/aDept/"+id, Dept.class);
  20.     }
  21. }
复制代码
4、Config的配置

在此文件里,增加了@LoadBalanced注解,该注解的作用是让RestTemplate有了负载均衡的能力,而且默认的负载均衡算法是轮询(也就是一个一个的尝试),可以使用系统配备的负载均衡算法,也可以自己写自己的负载均衡算法。
  1. package com.you.config;
  2. import com.netflix.loadbalancer.IRule;
  3. import com.netflix.loadbalancer.RandomRule;
  4. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.web.client.RestTemplate;
  8. @Configuration
  9. public class ConfigBean {
  10.     @Bean
  11.     @LoadBalanced  //ribbon
  12.     /*配置负载均衡实现RestTemplate*/
  13.     /*IRule*/
  14.     /*RoundRobinRule 轮询 */
  15.     /*RandomRule 随机*/
  16.     /*AvailabilityFilteringRule 优先过滤掉跳闸、访问故障的服务,对剩下的进行轮询 */
  17.     public RestTemplate getRestTemplate() {
  18.         return new RestTemplate();
  19.     }
  20. }
复制代码
5、启动类的配置
  1. package com.you;
  2. import com.tan.tanRule;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.cloud.netflix.ribbon.RibbonClient;
  7. @SpringBootApplication
  8. @EnableEurekaClient
  9. /*下面是处理负载均衡算法*/
  10. @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = tanRule.class)
  11. public class DeptConsumer_80 {
  12.     public static void main(String[] args) {
  13.         SpringApplication.run(DeptConsumer_80.class,args);
  14.     }
  15. }
复制代码
三、Ribbon实现负载均衡



为了实现负载均衡,扩充一下服务提供者,将原来的一个服务提供者,改为三个。
    新建三个module,springboot-provider-8002、springboot-provider-8003。参考springboot-provider-8001,修改application.xml(主要是端口号,数据库名,instance-id),其中application-name要保持一致。和微服务的名字一样。


    启动Eureka_7001,启动这个三个提供者,根据自己的情况,如果电脑性能比较差,可以少启动一个。启动consumer_80。
访问consumer_80配置的Getmapping地址,然后不断的刷新,会看到依次访问三个数据库,并且一直重复,这就是默认的负载均衡算法:轮询

四、设计负载均衡算法


1、80启动类的改动

@RibbonClient()注释的应用,在psvm上面添加该注释,其具体内容为@RibbonClient(name = “SPRINGCLOUD-PROVIDER-DEPT”,configuration = tanRule.class),其中name的值即为微服务的名字,configuration的值对应的就是自己写的路由类



2、自定义路由类

需要注意,自定义的路由类,不可以用启动类放在同一目录,一般要比启动类高一级目录,放在同一目录下,需要配置CompentScan。

  1. package com.tan;
  2. import com.netflix.loadbalancer.IRule;
  3. import com.netflix.loadbalancer.RandomRule;
  4. import org.springframework.context.annotation.Bean;
  5. public class tanRule {
  6.     @Bean
  7.     public IRule myRule()
  8.     {
  9.         return new tanRandomRule();
  10.     }
  11. }
复制代码
3、负载均衡算法的实现

可以模仿系统中的负载均衡算法,撰写自己的负载均衡算法,如下面的例子即为:每个端口的提供者访问5次,然后切换下一个端口,全部访问完成后则重新开始,代码如下:
  1. package com.tan;
  2. import com.netflix.client.config.IClientConfig;
  3. import com.netflix.loadbalancer.AbstractLoadBalancerRule;
  4. import com.netflix.loadbalancer.ILoadBalancer;
  5. import com.netflix.loadbalancer.Server;
  6. import java.util.List;
  7. import java.util.concurrent.ThreadLocalRandom;
  8. public class tanRandomRule extends AbstractLoadBalancerRule {
  9.    int total = 0;
  10.    int currentIndex = 0;
  11.    public tanRandomRule() {
  12.    }
  13.    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
  14.    public Server choose(ILoadBalancer lb, Object key) {
  15.        if (lb == null) {
  16.            return null;
  17.        } else {
  18.            Server server = null;
  19.            while(server == null) {
  20.                if (Thread.interrupted()) {
  21.                    return null;
  22.                }
  23.                List<Server> upList = lb.getReachableServers();
  24.                List<Server> allList = lb.getAllServers();
  25.                if(total<5)
  26.                {
  27.                    server = (Server)upList.get(currentIndex);
  28.                    total++;
  29.                }else{
  30.                    total = 0;
  31.                    currentIndex++;
  32.                    if(currentIndex>2)
  33.                    {
  34.                        currentIndex = 0;
  35.                    }
  36.                    server = (Server)upList.get(currentIndex);
  37.                }
  38.                System.out.println("CurrentIndex:"+currentIndex);
  39.                System.out.println("Total:"+total);
  40.                System.out.println("sever 的值是:"+server);
  41.                if (server == null) {
  42.                    Thread.yield();
  43.                } else {
  44.                    if (server.isAlive()) {
  45.                        return server;
  46.                    }
  47.                    server = null;
  48.                    Thread.yield();
  49.                }
  50.            }
  51.            return server;
  52.        }
  53.    }
  54.    protected int chooseRandomInt(int serverCount) {
  55.        return ThreadLocalRandom.current().nextInt(serverCount);
  56.    }
  57.    public Server choose(Object key) {
  58.        return this.choose(this.getLoadBalancer(), key);
  59.    }
  60.    public void initWithNiwsConfig(IClientConfig clientConfig) {
  61.    }
  62. }
复制代码
到此这篇关于SpringCloud Netflix Ribbon超详细讲解的文章就介绍到这了,更多相关SpringCloud Netflix Ribbon内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行