一、Ribbon概述
SpringCloud Ribbon 是基于Netflix Ribbon实现的一套客户端,负载均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用,Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是配置文件中列出Load Banlancer (简称LB) 后面所有的机器,Ribbon都会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
官网: https://github.com/Netflix/ribbon/wiki/Getting-Started
Ribbon已经进入维护模式!未来的替换方案:Load Banlancer
1、Ribbon能作什么
1.1 LB (负载均衡)
LB 负载均衡 Load balance 是什么
简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
常见的负载均衡有软件 Nginx LVS 硬件F5等
常见的负载均衡算法
- 轮询:为第一个请求选择健康池中的第一个后端服务器,然后按顺序往后依次选择,直到最后一个,然后循环。
- 最小连接:优先选择连接数最少,也就是压力最小的后端服务器,在会话较长的情况下可以考虑采取这种方式。
- 散列:根据请求源的 IP 的散列(hash)来选择要转发的服务器。这种方式可以一定程度上保证特定用户能连接到相同的服务器。如果你的应用需要处理状态而要求用户能连接到和之前相同的服务器,可以考虑采取这种方式。
Ribbon本地负载均衡客户端VS Nginx 服务端负载均衡区别
- Nginx是服务器负载均衡,客户端所有请求都会交给Nginx,然后由Nginx实现转发请求,即负载均衡是由服务端实现的
- Ribbon 本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术
1.1.2 集中式 LB
- 集中式LB:即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5,也可以是软件,如Nginx),由该设施负责把访问请求通过某种策略转发至服务的提供方。
1.1.3 进程内 LB
- 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个何时的服务器。
- Ribbon就属于是进程内LB, 它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。
一句话总结Ribbon:Ribbon是实现负载均衡的一套客户端工具结合RestTemplate实现调用。
二、负载均衡演示
2.1 架构说明
总结:Ribbon其实就是一个软负载均衡的客户端组件。
它可以和其他所需请求的客户端结合使用,和eureka结合只是其中一个实例
2.1.1 Ribbon在工作室分成两步
- 第一步先选择EurekaServer,它优先选择在同一个区域内负载较少的server
- 第二部再根据用户指定的策略,再从server取到的服务注册列表中选择一个地址。
其中Ribbon提供了多种策略:比如 轮询,随机和根据响应时间加权。
2.1.2 为什么没有引入Ribbon也可以完成负载均衡?
之前我们写样例的时候没有引入spring-cloud-start-ribbon也可以使用ribbon我们通过一个注解:@LoadBalanced赋予了RestTemplate负载均衡的能力;
原因是spring-boot-netfix-eureka-client自带了spring-starter-ribbon引用
因此我们不需要再次噖日Ribbon坐标,因为我们已经引入了spring-boot-netfix-eureka-client,里面自带Ribbon包。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.2. 二说RestTemplate的使用
为什么说它: 所谓的负载均衡,就是Ribbon结合RestTemplate实现调用微服务之间的调用。
2.2.1 getForObject方法/getForEntity方法
getForObject()
// 返回对象为响应体中数据转化成的对象,基本上可以理解为JSONgetForEntity()
// 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等。
------------------ getForObject() --------------------------------------
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
// 返回对象为响应体中数据转化成的对象,基本上可以理解为JSO
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
------------------ getForEntity() --------------------------------------
/**
* 测试getForEntity cloud-consumer-order80模块,OrderController类中
*/
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) {
// 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等。
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
log.info(entity.getStatusCode() + "\t" + entity.getHeaders());
return entity.getBody();
}else {
return new CommonResult<>(444, "操作失败");
}
}
这些方法对应着各种HTTP状态码,可以用来判断返回的entity对象包含的是哪种状态码。
可以跑通。可以用entity获取更详细的信息,比如头信息,响应体,状态码等。
_log_.info(entity.getStatusCode() + "\t" + entity.getHeaders());
2.2.2 postForObject/postForEntity
----------------------------postForObject------------------------------
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
log.info("80收到的参数:" + payment.toString());
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
----------------------------postForEntity------------------------------
/**
* 测试postForEntity cloud-consumer-order80模块,OrderController类中
*/
@GetMapping("/consumer/payment/postForEntity/create")
public CommonResult<Payment> create2(Payment payment) {
log.info("80收到的参数:" + payment.toString());
ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
log.info(entity.getHeaders() + "\t" +entity.getStatusCode());
return entity.getBody();
} else {
return new CommonResult<>(404, "操作失败");
}
}
三、Ribbon核心组件:IRule接口
3.1. IRule接口的各实现类,以及对应功能
根据特定算法从服务列表中选取一个要访问的服务。
IRule接口主要的实现类:
- com.netflix.loadbalancer.RoundRobinRule:轮询
- com.netflix.loadbalancer.RandomRule:随机
- com.netflix.loadbalancer.RetryRule:先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试
- WeightedResponseTimeRule:对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择
- BestAvailableRule:会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
- AvailabilityFilteringRule:先过滤掉故障实例,再选择并发较小的实例
- ZoneAvoidanceRule:默认规则,复合判断server所在区域的性能和server的可用性选择服务器
3.2. 如何替换负载均衡算法
①修改cloud-consumer-order80
②负载均衡配置类注意事项
注意配置类细节:官方文档明确给出了警告:这个自定义负载均衡配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的了。
什么是@ComponentScan
@SpringBootApplication注解中包含了@ComponentScan注解也就是说@SpringBootApplication标注的主配置类所在的包,以及所有子包都会被扫描到。
所以我们自定义的负载均衡配置类不能跟主启动类在同一个包下。
③新建com.atguigu.myrule包,将自定义负载均衡配置类MySelfRule放在改包下
写MySelfRule配置类
package com.atguigu.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();//定义为随机负载均衡算法
}
}
④主启动类添加@RibbonCilent注解
name里面的内容表示指明访问xxx服务时使用复杂均衡,configuration表示指明负载均衡策略
@SpringBootApplication
@EnableEurekaClient
//指明访问的服务CLOUD-PAYMENT-SERVICE,以及指定负载均衡策略
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
⑤启动cloud-consumer-order80测试
测试成功,访问http://localhost/consumer/payment/get/31 也可以
四、负载均衡算法
4.1 原理
轮循负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务重启后rest接口计数从1开始。
List<ServiceInstance> instances = doscoveryClient.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
如此类推
4.2 源码
4.3 手写一个负载均衡算法
①8001/8001微服务改造:controller
@GetMapping(value = "/payment/lb")
public String getPaymentLB()
{
return serverPort;
}
②80微服务改造
ApplicationContextConfig去掉@LoadBalance注解
③创建LoadBalancer接口
新建com.atguigu.springcloud.lb包
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
④创建LoadBalancer接口的实现类MyLoadBalancer
@Component
public class MyLoadBalancer implements LoadBalancer{
private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncrement() {
int current;
int next;
//从下面的分析中得知:该循环主要是得到next值,单机是每循环一次返回一次next
//高并发时:就不是这种情况了。因为数字会被抢占。
//自旋锁
do {
current = this.atomicInteger.get();
//考虑到极端情况,atomicInteger最大值为2147483647
//当请求次数超过这个值的时候,从0开始
next = current >= 2147483647 ? 0 : current + 1;
//compareAndSet方法使用了CAS机制,判断current是否变化,如果变了自旋,反之更新current
/**
* 当atomicInteger=0时,current=0, next=1
* atomicInteger和current进行比较,相等时返回true将atomicInteger更新为next,1,取反跳出循环,再返回next
* 当atomicInteger=2147483647时,current=2147483647,next=0
* atomicInteger和current进行比较,相等时返回true将atomicInteger更新为next, 0,取反跳出循环,再返回next
*
* 如果是高并发时,则需要判断当前线程获得的current值跟atomicInteger的值是否相等,
* 如果不相等则表示其他线程已经操作了atomicInteger,自旋。
* 这就是乐观锁的一个实现
*/
}while (!this.atomicInteger.compareAndSet(current, next));
System.out.println("************第几次访问次数:" + next);
return next;
}
//负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标
// 每次服务重启动后rest接口计数从1开始。
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
//计算当前访问应该分配给哪台服务器处理
int index = getAndIncrement() % serviceInstances.size();
//返回目标服务器
return serviceInstances.get(index);
}
}
⑤修改OrderController
@Resource //自动注入自定义的MyLoadBalancer类
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
/**
* 测试自己的轮循算法
*/
@GetMapping(value = "/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);
}