SpringCloud客户端负载均衡器Ribbon

本文介绍了SpringCloudRibbon作为NetflixRibbon的扩展,用于客户端负载均衡。内容涵盖了Ribbon的基本概念、作用、负载均衡分类、架构、整合Eureka的示例,以及如何自定义负载均衡策略和手写本地负载均衡器的实现。
摘要由CSDN通过智能技术生成

大纲


Ribbon是什么

简介

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

image.png

作用

  • Ribbon可以为客户端微服务提供负载均衡功能
  • LB负载均衡(Load Balance)是什么
  • 简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。
    • 常见的负载均衡有软件Nginx,LVS,硬件 F5等。
    • Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别
    • Nginx是服务器负载均衡,客户端所有请求都会交给nginx,然后由nginx实现转发请求。即负载均衡是由服务端实现的。
    • Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。

负载均衡的分类

  • 集中式LB
    • 即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5, 也可以是软件,如nginx), 由该设施负责把访问请求通过某种策略转发至服务的提供方;
  • 进程内LB
    • 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。
    • Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

Ribbon负载均衡架构

image.png

  • Ribbon在工作时分成两步
  • 第一步先选择 EurekaServer ,它优先选择在同一个区域内负载较少的server.
  • 第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。
  • 小结 : Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。

SpringCloud整合Ribbon演示

修改原有Eureka中的Consumer80

image.png

image.png

  • 四个方法
    在这里插入图片描述

  • 两种请求方式

    • GET请求方式
<T> T getForObject(String url, Class<T> responseType, Object... uriVariables);<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables);<T> T getForObject(URI url, Class<T> responseType);<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables);<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables);<T> ResponseEntity<T> getForEntity(URI var1, Class<T> responseType);
  • POST请求方式
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType);
  • postForEntity返回对象需要调用getBody()进行返回

image.png

GET http://localhost:80/consumer/payment/getObj/1

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 13 Sep 2023 15:01:40 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "code": 200,
  "message": "successful query data to id =1 from port number : 8001",
  "data": {
    "id": 1,
    "serial": "ljzTest01"
  }
}

Response code: 200; Time: 1057ms; Content length: 116 bytes
GET http://localhost:80/consumer/payment/getEntity/1

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 13 Sep 2023 15:04:05 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "code": 200,
  "message": "successful query data to id =1 from port number : 8002",
  "data": {
    "id": 1,
    "serial": "ljzTest01"
  }
}

Response code: 200; Time: 204ms; Content length: 116 bytes
  • 结果: 两次访问的端口号均不相同,原因在于使用了ribbon客户端负载均衡器,其负载均衡策略为轮询(交替访问)

Ribbon核心组件IRule

简介

  • IRule是什么?
    • IRule是Ribbon组件中的一个接口
  • IRule的作用?
    • 根据特定算法中从服务列表中选取一个要访问的服务
  • Ribbon类继承结构图

image.png

切换默认负载均衡策略

  • 修改模块cloud-consumer-order80

官方文档明确给出了警告:

  • 这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。

image.png

  • 修改默认配置所创建的配置类不能存在于被@SpringBootApplication所注解的主启动类包路径范围内
  • 新建packagetop.ljzstudy.myrule

image.png

  • 创建配置类MySelfRule
package top.ljzstudy.myrule;

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

@Configuration
public class MySelfRule{
    @Bean
    public IRule myRule(){
        return new RandomRule();//定义为随机
    }
}
  • 在主启动类添加开启Ribbon负载均衡器客户端@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
package top.ljzstudy.springcloud;

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;
import top.ljzstudy.myrule.MySelfRule;


@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class) //使用自定义负载均衡策略
public class MainApp80{
    public static void main(String[] args){
        SpringApplication.run(MainApp80.class,args);
    }
}

GET http://localhost:80/consumer/payment/getObj/1

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 13 Sep 2023 15:29:05 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "code": 200,
  "message": "successful query data to id =1 from port number : 8001",
  "data": {
    "id": 1,
    "serial": "ljzTest01"
  }
}

Response code: 200; Time: 92ms; Content length: 116 bytes
  • 通过配置类将默认轮询方式改为随机会出现连续多次访问均为8001,不在出现依次8001和8002交替出现的情况

Ribbon负载均衡算法

原理

负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ,每次服务重启动后rest接口计数从1开始。

List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

如:   List [0] instances = 127.0.0.1:8002
List [1] instances = 127.0.0.1:8001

8001+ 8002 组合成为集群,它们共计2台机器,集群总数为2, 按照轮询算法原理:

当总请求数为1时: 1 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位2时: 2 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
当总请求数位3时: 3 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
当总请求数位4时: 4 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
如此类推......

RoundRibbonRule源码

手写自定义本地负载均衡器

  • 修改服务提供者Payment8001/8002controller
//添加访问服务端口方法,用于校验负载均衡器效果
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
    return serverPort;
}
  • 对客户端ConsumerOrder80进行修改
    • 将@LoadBalanced注解取消
package top.ljzstudy.springcloud.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 ApplicationContextConfig {
    @Bean
    //@LoadBalanced//使用LoadBalance注解赋予RestTemplate负载均衡能力
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

  • 创建LoadBalancer接口
package top.ljzstudy.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

public interface LoadBalancer {
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

  • 编写LoadBalancer接口实现类
package top.ljzstudy.springcloud.lb.impl;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import top.ljzstudy.springcloud.lb.LoadBalancer;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalancerImpl implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*****next: " + next);
        return next;
    }


    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
  • 修改OrderController
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalancer loadBalancer;

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB()
    {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if(instances == null || instances.size()<=0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }
  • 测试依次启动注册中心集群7001/7002和服务提供者8001/8002,最后启动服务消费者80

1694623778725.png

GET http://localhost:80/consumer/payment/lb

HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 4
Date: Wed, 13 Sep 2023 16:47:39 GMT
Keep-Alive: timeout=60
Connection: keep-alive

8001

Response code: 200; Time: 78ms; Content length: 4 bytes
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝士君(Java 版)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值