Ribbon
简介
Spring Cloud Ribbon 是基于 Netflix Ribbon 实现的一套客户端负载均衡的工具。
简单的说, Ribbon 是 Netflix 发布的开源项目, 主要功能是提供
客户端的软件负载均衡算法和服务调用
。Ribbon 客户端组件提供一系列完善的配置项如连接超时、重试等。
简单的说, 就是在配置文件中列出 Load Balancer (简称LB) 后面所有的机器, Ribbon 会自动的帮助你基于某种规则(如简单轮询、随机连接等)去连接这些机器。我们很容易使用 Ribbon 实现自定乂的负载均衡算法。
LB(负载均衡)
简介
简单的说就是将用户的请求平摊的分配到多个服务上, 从而达到系统的 HA (高可用)。
常见的负载均衡有软件
Nginx、LVS,
硬件F5
等。
Ribbon 本地负载均衡客户端 和 Nginx 服务端负载均衡区别
- Nginx 是服务器负载均衡, 客户端所有请求都会交给 nginx, 然后由 ngInx 实现转发请求。
即负载均衡是由服务端实现的
。- Ribbon 本地负载均衡, 在调用微服务接口时候, 会在注册中心上获取注册信息服务列表之后缓存到 JVM 本地, 从而在本地实现 RPC 远程服务调用技术。
- 举例
牙疼首先选择科室 --> Nginx
确定科室后选择医生 --> Ribbon
- 集中式 LB
- 即在服务的消费方和提供方之间使用
独立的
LB 设施(可以是硬件, 如 F5, 也可以是软件, 如 ngInx), 由该设施负责把访问请求通过某种策略转发至服务的提供方- 进程内LB
- 将 LB 逻辑集成到消费方, 消费方从服务注册中心获知有哪些地址可用, 然后自己再从这些地址中选择出一个合适的服务器。
- Ribbon 就属于进程內 LB, 它只是—个类库,
集成于消费方进程
, 消费方通过它来获取到服务提供方的地址。
Ribbon在工作时分成两步
- 先选择 Eureka Server, 它优先选择在同一个区域内负载较少的 server
- 第二步再根据用户指定的策略, 在从 server 取到的服务注册列表中选择个地址
- 其中 Ribbon提供了多种策略 : 比如轮询、随机和根据晌应时间加权。
消费者集成Ribbon
Pom
此依赖已集成 Ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
负载均衡算法
IRule
根据特定算法从服务列表中选取一个要访问的服务
自带规则
算法 | 说明 |
---|---|
RoundRobinRule | 轮询「默认」 |
RandomRule | 随机 |
RetryRule | 先按照 RoundRobinRule 的策略获取服务,如果获取服务失败则在指定时间内会进行重试 |
WeightedResponseTimeRule | 对 RoundRobinRule(轮询) 的扩展,响应速度越快的实例选择权重越大,越容易被选择 |
BestAvailableRule | 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务 |
AvailabilityFilteringRule | 先过滤掉故障实例,再选择并发较小的实例 |
ZoneAvoidanceRule | 默认规则,复合判断server所在区域的性能和server的可用性选择服务器 |
替换规则
1、说明
官方文档明确给出了警告 :
这个自定义配置类不能放在
@ComponentScan
所扫描的当前包下以及子包下
, 否则我们自定义的这个配置类就会被所有的 Ribbon 客户端所共享, 达不到特殊化定制的目的了。
SpringBoot 的主启动类会被
@ComponentScan
所扫描到
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OXvhjxct-1614157552255)(https://gitee.com/le_xiaobei/image/raw/master/img/20210224151608.png)]
2、新建包
新建
myrule
使其和 SpringBoot 主启动类所在包同级
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rkKBFCZE-1614157552262)(https://gitee.com/le_xiaobei/image/raw/master/img/20210224151950.png)]
3、新建类
在
myrule
包下新建 MySelfRule.java
@Configuration
public class MySelfRule
{
@Bean
public IRule myRule()
{
return new RandomRule();//定义为随机
}
}
4、主启动类
SpringBoot 主启动类加上
RibbonClient
- name:微服务名(同一种生产者微服务名应该一样)
- configuration:负载均衡配置类
注意
- name :「
微服务名大写,与 Eureka 中显示的 微服务名保持一致
」
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PROVIDER-PAYMENT",configuration= MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
轮询算法
原理
rest 接口第几次请求数 % 务器集群总数量 = 实际调用服务器位置下标, 每次服务重启动后 rest 接口计数从 1 开始。
List<ServiceInstance> instances= discovery Client. 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
以此类推……
源码
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
//列出活着(UP)的微服务
List<Server> reachableServers = lb.getReachableServers();
//列出该服务提供者的全部微服务
List<Server> allServers = lb.getAllServers();
//UP 数
int upCount = reachableServers.size();
//ALL 数
int serverCount = allServers.size();
//如果其中一个数为0则打印警告日志并返回空
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
//获得下一个微服务提供者
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
原理的代码实现
compareAndSet
- 自旋锁
- 比较并交换
private int incrementAndGetModulo(int modulo) {
for (;;) {
//当前 默认为0
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
手写轮询算法
生产者
controller
新增
getPaymentLB()
方法
@GetMapping(value = "/lb")
public String getPaymentLB()
{
return serverPort;
}
消费者
config
去掉
@LoadBalanced
@Configuration
public class ApplicationContextConfig {
@Bean
//@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
lb
新建 lb 包并新建
LoadBalancer
接口
package com.mrw.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer
{
//获取全部的微服务
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
新建
MyLB
类
package com.mrw.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class MyLB 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;
}
//负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 ,每次服务重启动后rest接口计数从1开始。
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
controller
引入手写的
LoadBalancer
package com.mrw.springcloud.controller;
import com.mrw.springcloud.entities.CommonResult;
import com.mrw.springcloud.entities.Payment;
import com.mrw.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
/**
* @author: weijiubo
* @date: 2021/2/6 17:33
* @description:
*/
@RestController
@Slf4j
public class OrderController {
// public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PROVIDER-PAYMENT";
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
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);
}
}
访问测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hmESrcDQ-1614157552266)(https://gitee.com/le_xiaobei/image/raw/master/img/20210224165856.png)]