大纲
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延申 -
官方文档

-
四个方法 | postForEntity
getForEntity | 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等 | | — | — | | postForObject
getForObject | 返回对象为响应体中数据转化成的对象,基本上可以理解为Json | -
两种请求方式
-
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()进行返回

-
测试 -
访问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所注解的主启动类包路径范围内
-
新建package top.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<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

-
访问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
原文始发于微信公众号(小李记录学习日常):SpringCloud客户端负载均衡器Ribbon
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/233387.html