大纲

Ribbon是什么

简介

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。

Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。

官网资料停更进维

作用

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负载均衡架构

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

SpringCloud整合Ribbon演示

修改原有Eureka中的Consumer80

环境说明

pom文件,参考《SpringCloud服务注册与发现之Eureka》一文中的pom文件的依赖

eureka本身已经整合ribbon,故无需修改pom文件Ribbon负载均衡实现需要结合RestTemplate

参考《SpringCloud服务注册与发现之Eureka》中单机Eureka构建过程中客户端构建模块 RestTemplate延申

官方文档

四个方法 两种请求方式

GET请求方式

T getForObject(String url, Class responseType, Object... uriVariables);

T getForObject(String url, Class responseType, Map uriVariables);

T getForObject(URI url, Class responseType);

ResponseEntity getForEntity(String url, Class responseType, Object... uriVariables);

ResponseEntity getForEntity(String url, Class responseType, Map uriVariables);

ResponseEntity getForEntity(URI var1, Class responseType);

POST请求方式

T postForObject(String url, @Nullable Object request, Class responseType, Object... uriVariables);

T postForObject(String url, @Nullable Object request, Class responseType, Map uriVariables);

T postForObject(URI url, @Nullable Object request, Class responseType);

ResponseEntity postForEntity(String url, @Nullable Object request, Class responseType, Object... uriVariables);

ResponseEntity postForEntity(String url, @Nullable Object request, Class responseType, Map uriVariables);

ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType);

postForEntity返回对象需要调用getBody()进行返回

测试

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

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

访问 http://localhost:80/consumer/payment/getEntity/1

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类继承结构图

切换默认负载均衡策略

修改模块cloud-consumer-order80

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

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

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

新建packagetop.ljzstudy.myrule

创建配置类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);

}

}

访问http://localhost/consumer/payment/getObj/1

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 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 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 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 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

访问http://localhost:80/consumer/payment/lb

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

好文推荐

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。