SpringCloud Netflix---Ribbon负载均衡

news/2024/7/10 2:38:57 标签: 微服务, 负载均衡, ribbon, springcloud

练习代码gitee地址: https://gitee.com/longjiamou/spring-cloud-netflix.git

1. 什么是Ribbon

       Ribbon是SpringCloud Netflix的一套客户端负载均衡工具,也可以说是一个开源的SpringCloud项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间服务连接在一起,它还提供一系列完整的配置项,比如:连接超时,重试等等。就是说: 在我们配置文件中列出LoadBalancer(负载均衡)后面的所有集群服务,比如我们在Eureka中所注册的一个个服务,Ribbon会自动的帮助我们基于某种规则(如:轮询,随机连接等等)去连接我们想要连接的服务。

       比如:Eureka中有两个一样的服务提供者(服务名相同,端口不同,可以简单理解为两个相同的项目,只是端口不一样而已),当我们的服务消费者想要调用服务提供者中的某一个方法,我们可以使用指定的规则(负载均衡)来将我们的请求发送到两个服务提供者的其中一个,比如:第一次访问了服务提供者A,第二次就访问服务提供者B。

       我们还可以使用Ribbon实现自定义的负载均衡算法,而且当Eureka和Ribbon一起使用时,我们可以根据服务名来访问相关的服务,而不是通过指定的IP和端口。

2. 什么是负载均衡

       负载均衡(Load Balance,简称“LB”),在微服务或者分布式文件系统中,简单来说就是将用户的请求根据指定的规则(负载均衡算法)来分配到多个服务上,从而达到系统的的高可用(HA)。
在这里插入图片描述

       如上图所示:当客户端向服务端发起请求时,我们可以通过负载均衡发送到指定的服务端,避免客户端所有的请求都发送到一个服务端中去,导致服务端出现宕机等情况。

       常见的负载均衡软件有:Nginx,Lvs等,其中Nginx是典型的反向代理负载均衡,使用起来也比较方便,是比较常用的工具。

负载均衡分类:

  • 集中式:即在服务的消费方和通过方使用独立的LB设施,如:Nginx,该设施负责把访问请求通过某种策略转发到服务提供方。
  • 进程式:将负载均衡逻辑集成到消费方,消费方从服务注册中心得到相关的可用服务地址,然后再从这些地址选出一个合适的服务去访问,Ribbon就属于这种,他只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

3. Ribbon负载均衡算法

在这里插入图片描述

       Ribbon负载均衡策略主要是通过IRule接口来作为桥梁,里面一共有10个方法实现了这个接口,这10个方法也是10中负载均衡策略,默认使用的是轮询算法,常用的有以下5种:

  1. RoundRobinRule(轮询算法): 所有的服务中,一个一个轮流访问

  2. RandomRule(随机算法): 随机访问一个个服务

  3. RetryRule(重试): 先按照RoundRobinRule的策略获取服务,如果获取失败则在制定时间内进行重试,获取可用的服务

  4. BestAviableRule(过滤): 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务

  5. WeightedResponseTimeRule(权重): 根据平均响应的时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高,刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够会切换到WeightedResponseTimeRule

算法分析: 随机算法,大部分情况下,如果我们需要自定义算法,我们可以重写AbstractLoadBalancerRule里面的choose方法即可。注意:如果想要使用自定义的算法,Java类的配置不能跟启动类放在同一级目录上,因为这样子会被我们的springboot扫描到,所以我们需要在不同级目录上建立我们的算法配置类,然后用户RibbonClient来指定相对应的算法类。详细情况可查看官方文档:http://docs.springcloud.cn/user-guide/ribbon/#ribbon-client。

public class RoundRobinRule extends AbstractLoadBalancerRule {
    public Server choose(ILoadBalancer lb, Object key) {
        //判断服务列表是否为空
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        } else {
            Server server = null;
            int count = 0;
            while(true) {
                if (server == null && count++ < 10) {
                    //获取可用的服务列表
                    List<Server> reachableServers = lb.getReachableServers();
                    //获取所有的服务列表
                    List<Server> allServers = lb.getAllServers();
                    //记录相对应的服务列表个数
                    int upCount = reachableServers.size();
                    int serverCount = allServers.size();
                    if (upCount != 0 && serverCount != 0) {
                        //从所有服务列表数的范围内随机取一个数
                        int nextServerIndex = this.incrementAndGetModulo(serverCount);
                        //根据随机获取的数字来获取到相对应的服务
                        server = (Server)allServers.get(nextServerIndex);
                        //如果这个服务为空,线程礼让
                        if (server == null) {
                            Thread.yield();
                        } else {
                            //如果这个服务可用,就返回这个服务
                            if (server.isAlive() && server.isReadyToServe()) {
                                return server;
                            }
                            server = null;
                        }
                        continue;
                    }
                    log.warn("No up servers available from load balancer: " + lb);
                    return null;
                }
                if (count >= 10) {
                    log.warn("No available alive servers after 10 tries from load balancer: " + lb);
                }
                return server;
            }
        }
    }
}

4. 简单使用

Ribbon使用原理分析:

在这里插入图片描述

       如上图所示:因为Ribbon是进程式的负载均衡(即集成到消费方),所以在服务消费方集成并设置Ribbon,在设置完后,首先向注册中心注册(在这里我们可以选择是否向注册中心注册自身),然后在注册中心中获取相对应的服务列表(服务名),然后再通过服务名根据相关的负载均衡算法来调用相关服务。

       简单点来说,使用顺序就是:

  1. 搭建服务提供者,并向服务注册中心注册
  2. 搭建服务消费者并配置Ribbon,并向服务注册中心注册
  3. 服务消费者在服务注册中心中获取相关的服务列表,即服务名
  4. 拿到服务名后,服务消费者就可以使用负载均衡算法来调用相关的服务

Ribbon配置和使用:

1.首先搭建相关的服务注册中心,服务提供者和服务消费者
在这里插入图片描述
2.搭建服务注册中心集群

       可参考上一篇Eureka服务注册:https://blog.csdn.net/I_am_fine_/article/details/124263100

3.搭建服务提供者server-provide-8083
在这里插入图片描述

testController控制类:

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class testController {
    @GetMapping("/test")
    public Object test(){
        return "我是8083端口,服务提供者1的helloworld";
    }
}

启动类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServerProvide8083Application {
    public static void main(String[] args) {
        SpringApplication.run(ServerProvide8083Application.class, args);
    }
}

application.yml配置文件:

server:
  port: 8083

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/,http://localhost:8082/eureka/
  instance:
    instance-id: service-provide-first-8083			#服务实例ID
spring:
  application:
    name: server-provider							#服务名(俩个做负载均衡的服务名要一致)

pom依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>springcloud-netfilx</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <artifactId>server-provide-8083</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

根模块pom文件配置: 如果不做模块的话,需自己导入Eureka,SpringCloud,SpringBoot等依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>springcloud-netfilx</artifactId>
    <version>1.0-SNAPSHOT</version>

    <modules>
        <module>eureka-8081</module>
        <module>eureka-8082</module>
        <module>server-provide-8083</module>
        <module>service-provide-two-8084</module>
        <module>server-customer-first-8085</module>
    </modules>


    <properties>
        <java.version>1.8</java.version>
        <spring.boot.version>2.3.2.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR8</spring.cloud.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

4.搭建服务消费者:server-provide-two-8084

server-provide-two-8084服务和server-provide-8083基本类似,只需改动以下相关代码即可:

testController:

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class testController {
    @GetMapping("/test")
    public Object test(){
        return "我是8084端口,服务提供者2的helloworld";
    }
}

application.yml配置文件:

server:
  port: 8084

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/,http://localhost:8082/eureka/
  instance:
    instance-id: service-provide-first-8084
spring:
  application:
    name: server-provider

启动类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceProvideTwo8084Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceProvideTwo8084Application.class, args);
    }

}

pom依赖: 将artifactId改成服务提供者2的即可,其他的一样

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>springcloud-netfilx</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <artifactId>server-provide-two-8084</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

5.搭建服务消费者:server-customer-first-8085
在这里插入图片描述

ConfigBean类: 重写一个RestTemplate的方法类,并将它注册成Bean给Spring来托管

package com.example.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 {

    @Bean
    @LoadBalanced   //负载均衡注解
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

testController测试类:

package com.example.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class testController {
    @Autowired
    private RestTemplate restTemplate;

    //private static final String REST_URL_PREFIX = "http://localhost:8081";
    //由原来的IP+端口访问变为服务名访问
    private static final String REST_URL_PREFIX = "http://SERVER-PROVIDER";

    @GetMapping("/consumer/test")
    public Object HelloWorld(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/test",String.class);
    }
}

启动类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
public class ServerCustomerFirst8085Application {

    public static void main(String[] args) {
        SpringApplication.run(ServerCustomerFirst8085Application.class, args);
    }
}

application.yml配置类:

server:
  port: 8085

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/,http://localhost:8082/eureka/
    register-with-eureka: false
spring:
  application:
    name: server-customer-first-8085

pom依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>springcloud-netfilx</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <artifactId>server-customer-first-8085</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Eureka客户端 -->
        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

6.启动相关服务并测试:
在这里插入图片描述

连续访问服务消费者的测试接口:
在这里插入图片描述
在这里插入图片描述
       从以上结果可以得出:Ribbon负载均衡搭建成功,也可以得出Ribbon默认的负载均衡算法是轮询算法。


http://www.niftyadmin.cn/n/1530012.html

相关文章

SpringCloud Netflix---Feigin服务调用

练习代码gitee地址&#xff1a; https://gitee.com/longjiamou/spring-cloud-netflix.git 1. 什么是Feigin Feigin是SpringCloud NetFlix中一个声明式&#xff08;就像调用本地方法一样调用远程方法&#xff09;的web service客户端&#xff0c;可以让微服务之间的调用变得更加…

SpringCloud Netflix---Hystrix服务治理

练习代码gitee地址&#xff1a; https://gitee.com/longjiamou/spring-cloud-netflix.git 1. 什么是服务雪崩 一个完整的微服务系统&#xff0c;其实是由很多服务组成的&#xff0c;每个服务之间都多多少少会存在一些依赖关系。如上图所示&#xff1a;假设用户的请求需要通过服…

SpringCloud Netflix---Zuul路由网关

练习代码gitee地址&#xff1a; https://gitee.com/longjiamou/spring-cloud-netflix.git 1. 什么是Zuul Zuul是SpringCloud Netflix里的一个组件之一&#xff0c;也称为路由网关&#xff0c;它本身也是一个微服务&#xff0c;可以在注册中心里注册&#xff0c;主要负责将用户…

SpringCloud---Config配置中心

练习代码gitee地址&#xff1a; https://gitee.com/longjiamou/spring-cloud-netflix.git 1. 什么是Config 随着微服务分布式系统的发展&#xff0c;每个系统都包含了许许多多的配置文件&#xff0c;而当我们在项目中修改配置文件时&#xff0c;会涉及到很多微服务对应的配置文…

SpringCloud Alibaba 简介

1. SpringCloud Alibaba的由来 2018年&#xff0c;SpringCloud Netfilx官方宣布SpringCloud NetFilx微服务相关系列的框架组件进入维护模式&#xff0c;意味着SpringCloud NetFilx将不再更新&#xff0c;而是对现有的组件进行一个维护&#xff0c;修改bug等。而SpringCloud生态…

Nacos服务注册与发现---Nacos简介以及原理

1. 什么是Nacos ​ ​ ​ ​ Nacos是SpringCloud Alibaba的一个服务治理的一个重要组件&#xff0c;英文全称Dynamic Naming and Configuration Service&#xff0c;顾名思义就是动态命名和配置服务&#xff0c;它不仅提供服务的注册与发现&#xff0c;还提供统一的配置…

Nacos服务注册与发现---Nacos的使用以及集群

1. Nacos的安装 Nacos的安装非常简单&#xff0c;我们只需前往官网下载相对应的压缩包&#xff0c;解压缩即可&#xff0c;因为Nacos本身可以理解为一个已经写好的服务。 1.前往官网下载相对应的Nacos压缩包&#xff1a; https://github.com/alibaba/nacos/releases 2.Nacos…

Docker容器---Docker简介与原理

1. 概述 1.1 容器概念 docker是一个容器&#xff0c;所谓容器&#xff0c;就是在隔离的环境运行的一个进程&#xff0c;如果进程停止&#xff0c;容器就会销毁。隔离的环境拥有自己的系统文件&#xff0c;ip地址&#xff0c;主机名等&#xff0c;kvm虚拟机&#xff0c;linux&a…