SpringCloud-03 Netflix Ribbon学习笔记

本文涉及的产品
传统型负载均衡 CLB,每月750个小时 15LCU
应用型负载均衡 ALB,每月750个小时 15LCU
网络型负载均衡 NLB,每月750个小时 15LCU
简介: SpringCloud-03 Netflix Ribbon学习笔记

在这里插入图片描述

一、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、客户端导入依赖

     <!--引入Eureka的依赖-->
     <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--引入ribbon-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
    </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,而是这个微服务的名字,也就是这个名字,如下。
在这里插入图片描述

package com.you.controller;

import com.you.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@ResponseBody
public class DeptComsumerController {
    @Autowired
    RestTemplate restTemplate;
//    public static final String REST_URL_PREFIX = "http://localhost:8001";
    public static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";

    @GetMapping("/consumer/dept/getDept/{id}")
    public Dept getDeptOfId(@PathVariable("id") Long id)
    {

        System.out.println(REST_URL_PREFIX+"/dept"+"/aDept/"+id);
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept" + "/aDept/"+id, Dept.class);
    }
}

4、Config的配置

在此文件里,增加了@LoadBalanced注解,该注解的作用是让RestTemplate有了负载均衡的能力,而且默认的负载均衡算法是轮询(也就是一个一个的尝试),可以使用系统配备的负载均衡算法,也可以自己写自己的负载均衡算法。

package com.you.config;


import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
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 {
    @Bean
    @LoadBalanced  //ribbon
    /*配置负载均衡实现RestTemplate*/
    /*IRule*/
    /*RoundRobinRule 轮询 */
    /*RandomRule 随机*/
    /*AvailabilityFilteringRule 优先过滤掉跳闸、访问故障的服务,对剩下的进行轮询 */
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

5、启动类的配置

package com.you;

import com.tan.tanRule;
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;

@SpringBootApplication

@EnableEurekaClient
/*下面是处理负载均衡算法*/
@RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT",configuration = tanRule.class)
public class DeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumer_80.class,args);
    }
}

三、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。
在这里插入图片描述

package com.tan;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;

public class tanRule {
    @Bean
    public IRule myRule()
    {
        return new tanRandomRule();
    }
}

## 3、负载均衡算法的实现
可以模仿系统中的负载均衡算法,撰写自己的负载均衡算法,如下面的例子即为:每个端口的提供者访问5次,然后切换下一个端口,全部访问完成后则重新开始,代码如下:

package com.tan;

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 tanRandomRule extends AbstractLoadBalancerRule {
   int total = 0;
   int currentIndex = 0;
   public tanRandomRule() {
   }

   @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();

               if(total<5)
               {
                   server = (Server)upList.get(currentIndex);
                   total++;
               }else{
                   total = 0;
                   currentIndex++;
                   if(currentIndex>2)
                   {
                       currentIndex = 0;
                   }
                   server = (Server)upList.get(currentIndex);
               }
               System.out.println("CurrentIndex:"+currentIndex);
               System.out.println("Total:"+total);
               System.out.println("sever 的值是:"+server);
               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) {
   }
}

在这里插入图片描述

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
相关文章
|
Cloud Native Java 对象存储
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
展望未来,随着5G、边缘计算等新技术的兴起,微服务架构的设计理念将会更加深入人心,Spring Cloud和Netflix OSS也将继续引领技术潮流,为企业带来更为高效、灵活且强大的解决方案。无论是对于初创公司还是大型企业而言,掌握这些前沿技术都将是在激烈市场竞争中脱颖而出的关键所在。
254 0
|
Java 对象存储 开发者
解析Spring Cloud与Netflix OSS:微服务架构中的左右手如何协同作战
Spring Cloud与Netflix OSS不仅是现代微服务架构中不可或缺的一部分,它们还通过不断的技术创新和社区贡献推动了整个行业的发展。无论是对于初创企业还是大型组织来说,掌握并合理运用这两套工具,都能极大地提升软件系统的灵活性、可扩展性以及整体性能。随着云计算和容器化技术的进一步普及,Spring Cloud与Netflix OSS将继续引领微服务技术的发展潮流。
262 0
|
负载均衡 算法 Java
除了 Ribbon,Spring Cloud 中还有哪些负载均衡组件?
这些负载均衡组件各有特点,在不同的场景和需求下,可以根据项目的具体情况选择合适的负载均衡组件来实现高效、稳定的服务调用。
1076 61
|
负载均衡 监控 网络协议
SpringCloud之Ribbon使用
通过以上步骤,就可以在Spring Cloud项目中有效地使用Ribbon来实现服务调用的负载均衡,提高系统的可靠性和性能。在实际应用中,根据具体的业务场景和需求选择合适的负载均衡策略,并进行相应的配置和优化,以确保系统的稳定运行。
509 15
|
负载均衡 Java Nacos
SpringCloud基础1——远程调用、Eureka,Nacos注册中心、Ribbon负载均衡
微服务介绍、SpringCloud、服务拆分和远程调用、Eureka注册中心、Ribbon负载均衡、Nacos注册中心
SpringCloud基础1——远程调用、Eureka,Nacos注册中心、Ribbon负载均衡
|
Cloud Native Java 对象存储
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
面向未来的架构设计:Spring Cloud和Netflix OSS在云原生环境下的发展趋势
217 1
|
监控 Java 对象存储
监控与追踪:如何利用Spring Cloud Sleuth和Netflix OSS工具进行微服务调试
监控与追踪:如何利用Spring Cloud Sleuth和Netflix OSS工具进行微服务调试
193 1
|
Java 对象存储 开发者
故障隔离与容错处理:Hystrix在Spring Cloud和Netflix OSS中的应用
故障隔离与容错处理:Hystrix在Spring Cloud和Netflix OSS中的应用
247 3
|
Java 开发工具 对象存储
简化配置管理:Spring Cloud Config与Netflix OSS中的动态配置解决方案
简化配置管理:Spring Cloud Config与Netflix OSS中的动态配置解决方案
221 2
|
消息中间件 Java 对象存储
数据一致性挑战:Spring Cloud与Netflix OSS下的分布式事务管理
数据一致性挑战:Spring Cloud与Netflix OSS下的分布式事务管理
217 2
下一篇
oss云网关配置