栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud Netflix---Ribbon负载均衡

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud Netflix---Ribbon负载均衡

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 reachableServers = lb.getReachableServers();
                    //获取所有的服务列表
                    List 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依赖:



    4.0.0

    
        com.example
        springcloud-netfilx
        1.0-SNAPSHOT
        
    

    server-provide-8083

    
        1.8
    

    
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
            1.4.6.RELEASE
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    


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



    4.0.0

    com.example
    springcloud-netfilx
    1.0-SNAPSHOT

    
        eureka-8081
        eureka-8082
        server-provide-8083
        service-provide-two-8084
        server-customer-first-8085
    


    
        1.8
        2.3.2.RELEASE
        Hoxton.SR8
    

    
        
            
                org.springframework.boot
                spring-boot-starter-parent
                ${spring.boot.version}
                pom
                import
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring.cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


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的即可,其他的一样



    4.0.0

    
        com.example
        springcloud-netfilx
        1.0-SNAPSHOT
        
    

    server-provide-two-8084

    
        1.8
    

    
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
            1.4.6.RELEASE
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    



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依赖:



    4.0.0

    
        com.example
        springcloud-netfilx
        1.0-SNAPSHOT
        
    

    server-customer-first-8085

    
        1.8
    

    
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
            1.4.6.RELEASE
        

        
        
            org.springframework.cloud
            spring-cloud-starter-ribbon
            1.4.6.RELEASE
        

        
            org.springframework.boot
            spring-boot-starter-web
        


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


6.启动相关服务并测试:

连续访问服务消费者的测试接口:


       从以上结果可以得出:Ribbon负载均衡搭建成功,也可以得出Ribbon默认的负载均衡算法是轮询算法。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820683.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号