概述
Ribbon是什么
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将NetFlix的中间层服务连接在一起。Ribbon的客户端组件提供一系列完整的配置项如:连接超时、重试等等。简单的说,就是在配置文件中列出 LoadBalancer(简称LB:负载均衡)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等等)去连接这些机器。我们也很容易使用Ribbon实现自 定义的负载均衡算法!
Ribbon能干嘛
LB,即负载均衡(Load Balance),在微服务或分布式集群中经常用的一种应用。
负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。
常见的负载均衡软件有 Nginx,Lvs 等等
Dubbo、SpringCloud中均给我们提供了负载均衡,SpringCloud的负载均衡算法可以自定义
负载均衡简单分类:
- 集中式LB
- 即在服务的消费方和提供方之间使用独立的LB设施
- 如之前学习的Nginx( 反向代理服务器 ),由该设施负责把访问请求通过某种策略转发至服务的提供方!
- 进程式LB
- 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地 址中选出一个合适的服务器。
- Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务 提供方的地址!
Ribbon的github地址 :https://github.com/NetFlix/ribbon
Ribbon配置初步
复制 springcloud-consumer-dept-80 工程 springcloud-consumer-dept-ribbon-80
1、主启动类名字修改下,用作区分
@SpringBootApplication
public class DeptConsumerRibbon80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumerRibbon80.class, args);
}
}
2、修改 pom.xml ,添加Ribbon相关的配置
<!-- 实体类 + web -->
<dependencies>
<!-- Ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<!-- spring-cloud-starter-eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jia</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
3、修改 application.yml , 追加Eureka的服务注册地址
server:
port: 80
#Eureka配置
eureka:
client:
register-with-eureka: false #false表示不向注册中心注册自己
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
4、对里面的 ConfigBean 方法加上注解 @LoadBalanced 在 获得Rest时加入Ribbon的配置;
@Configuration
public class ConfigBean {
// 配置负载均衡 实现RestTemplate
// RoundRobinRule 轮询
// RandomRule 随机
// RetryRule 会先按照轮询获取服务~如果服务获取失败,则会在指定时间内进行 重试
// AvailabilityFilteringRule : 会先过滤掉跳闸、访问故障的服务~ 剩下的进行轮询
@Bean
@LoadBalanced // //Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
5、主启动类 DeptConsumerRibbon80 添加 @EnableEurekaClient
// Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心地址和端口号
@SpringBootApplication
@EnableEurekaClient
public class DeptConsumerRibbon80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumerRibbon80.class, args);
}
}
6、修改 DeptConsumerController 客户端访问类,之前的写的地址是写死的,现在需要变化
// private static final String REST_URL_PREFIX = "http://localhost:8001";
// 通过 Ribbon 地址应该是一个变量,通过服务名访问
private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
7、先启动3个Eureka集群后,在启动springcloud-provider-dept-8001并注册进eureka
8、启动 DeptConsumerRibbon80
9、测试
http://localhost/consumer/dept/get/1
http://localhost/consumer/dept/list
10、小结
Ribbon 和 Eureka 整合后 Consumer 可以直接调用服务而不用再关心地址和端口号!
Ribbon负载均衡
架构说明
Ribbon在工作时分成两步
第一步先选择EurekaServer,它优先选择在同一个区域内负载均衡较少的Server。
第二步在根据用户指定的策略,在从server去到的服务注册列表中选择一个地址。
其中Ribbon提供了多种策略,比如轮询(默认),随机和根据响应时间加权重...等等
测试:
参考springcloud-provider-dept-8001,新建两份,分别为8002,8003!
全部复制完毕,修改启动类名称,修改端口号名称!
新建8002/8003数据库,各自微服务分别连接各自的数据库,复制DB1!
- 新建springcloud
- 新建springcloud02
- 新建springcloud03
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
`deptno` int(10) NOT NULL AUTO_INCREMENT,
`dname` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`db_source` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`deptno`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES (1, '开发部', 'springcloud');
INSERT INTO `dept` VALUES (2, '人事部', 'springcloud');
INSERT INTO `dept` VALUES (3, '财务部', 'springcloud');
INSERT INTO `dept` VALUES (4, '市场部', 'springcloud');
INSERT INTO `dept` VALUES (5, '运维部', 'springcloud');
INSERT INTO `dept` VALUES (15, NULL, 'springcloud');
SET FOREIGN_KEY_CHECKS = 1;
修改8002/8003各自的YML文件
- 端口
- 数据库连接
- 实例名也需要修改
-
instance: instance-id: springcloud-provider-dept8002 # 修改 eureka 上的默认信息
- 对外暴露的统一的服务实例名【三个服务名字必须一致!】
-
application: name: springcloud-provider-dept
启动3个Eureka集群配置区
启动3个Dept微服务并都测试通过
http://localhost:8001/dept/list
http://localhost:8002/dept/list
http://localhost:8003/dept/list
启动springcloud-consumer-dept-ribbon-80
客户端通过Ribbon完成负载均衡并访问上一步的Dept微服务
http://localhost/consumer/dept/list
多刷新几次注意观察结果!
总结:
Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和 Eureka结合只是其中的一个实例。
Ribbon核心组件IRule
IRule:根据特定算法从服务列表中选取一个要访问的服务!
- RoundRobinRule【轮询】
- RandomRule 【随机】
- AvailabilityFilterRule【会先过滤掉由于多次访问故障而处于断路器跳闸的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问】
- WeightedResponseTimeRule【根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大,被选中的概率越高,刚启动时如果统计信息不足,则使用RoundRobinRule策略,等待统计信 息足够,会切换到WeightedResponseTimeRule】
- RetryRule【先按照RoundRobinRule的策略获取服务,如果获取服务失败,则在指定时间内会进行重试,获取可用的服务】
- BestAvailableRule【会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务】
- ZoneAvoidanceRule【默认规则,复合判断server所在区域的性能和server的可用性选择服务器】
查看分析源码:
- IRule
- ILoadBalancer
- AbstractLoadBalancer
- AbstractLoadBalancerRule:这个抽象父类十分重要!核心
- RoundRobinRule
自定义Ribbon
修改 springcloud-consumer-dept-ribbon-80
主启动类添加 @RibbonClient 注解
在启动该微服务的时候就能去加载我们自定义的Ribbon配置类,从而使配置类生效,例如:
@RibbonClient(name="SPRINGCLOUD-PROVIDERDEPT",configuration= MyRule.class)
官方文档明确给出了警告: (https://www.springcloud.cc/spring-cloud-netflix.html)
这个自定义配置类不能放在 @ComponentScan 所扫描的当前包以及子包下,否则我们自定义的这个配置 类就会被所有的Ribbon客户端所共享,也就是说达不到特殊化定制的目的了!
步骤
1、由于有以上配置细节原因,我们建立一个包 com.jia.myRule
2、在这里新建一个自定义规则的Rubbion类
package com.jia.myRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRule {
@Bean
public IRule jiaRule(){
return new JiaRandomRule(); // 自定义 RandomRule
}
}
3、在主启动类上配置我们自定义的Ribbon
package com.jia.springcloud;
import com.jia.myRule.MyRule;
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;
// Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心地址和端口号
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name="SPRINGCLOUD-PROVIDERDEPT",configuration= MyRule.class)
public class DeptConsumerRibbon80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumerRibbon80.class, args);
}
}
4、启动所有项目,访问测试,看看我们编写的随机算法,现在是否生效!
自定义规则深度解析
1、问题:依旧轮询策略,但是加上新需求,每个服务器要求被调用5次,就是以前每一个机器一次,现 在每个机器5次;
2、解析源码:RandomRule.java , IDEA直接点击进去,复制出来,变成我们自己的类
仔细分析阅读源码
/**
* Randomly choose from all living servers
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes
* only get more restrictive.
*/
return null;
}
int index = chooseRandomInt(serverCount);
server = upList.get(index);
if (server == null) {
/*
* The only time this should happen is if the server list were
* somehow trimmed. This is a transient condition. Retry after
* yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
参考源码修改为我们需求要求的 JiaRandomRule.java
package com.jia.myRule;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class JiaRandomRule extends AbstractLoadBalancerRule {
// 每个机器访问 5 次,换下一个服务(3个)
private int total = 0;
private int currentIndex = 0;
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
} else {
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();// 获得活着的服务
List<Server> allList = lb.getAllServers();// 获得所有的服务
int serverCount = allList.size();
if (serverCount == 0) {
return null;
}
// int index = this.chooseRandomInt(serverCount);// 生成区间随机数
// server = upList.get(index);// 从活着的服务中随机获取一个
// -==============================================================================
if (total < 5) {
server = upList.get(currentIndex);
total++;
} else {
total = 0;
currentIndex++;
if (currentIndex >= upList.size()) {
currentIndex = 0;
}
server = upList.get(currentIndex); // 从活着的服务中,获取指定的服务来进行操作
}
// -==============================================================================
if (server == null) {
Thread.yield();
} else if (server.isAlive()) {
return server;
}
server = null;
Thread.yield();
}
return server;
}
}
protected int chooseRandomInt(int serverCount) {
return ThreadLocalRandom.current().nextInt(serverCount);
}
public Server choose(Object key) {
return this.choose(this.getLoadBalancer(), key);
}
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}
调用,在我们自定义的IRule方法中返回刚才我们写好的随机算法类
package com.jia.myRule;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRule {
@Bean
public IRule jiaRule(){
return new JiaRandomRule(); // 自定义 RandomRule
}
}