目录
什么是Ribbon
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。
Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,
Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法。
常见的负载均衡软件有:Nginx,LVS,硬件有F5(一个字贵)等
在深圳很多肯德基/麦当劳,都有客户端/人工点餐,在多个客户端使用中,正常(一般)人都会去人少的那一台机器,这样效率更高;Ribbon就是负责这个效率的
Ribbon做什么用的
LB负载均衡 分两种
集中式LB(偏硬件)
即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5, 也可以是软件,如nginx), 由该设施负责把访问请求通过某种策略转发至服务的提供方;
进程内LB(偏软件)
将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。
Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。
点击进入 Ribbon在github地址
架构说明:
Ribbon在工作时分成两步
第一步先选择 EurekaServer ,它优先选择在同一个区域内负载较少的server.
第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。
其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。
Ribbon的初步配置
修改springcloud-consumer-dept-80工程/客户端
完成真正的通过微服务名字从eureka上找到并访问
需要获取新的功能/插件 (spring boot项目中)
-
GAV-maven pom.xml文件 jar包导入
-
注解支持 对应的@EnableXXX
③ 编码 业务
<dependencies>
<dependency><!-- 自己定义的api -->
<groupId>com.jiangjy.springcloud</groupId>
<artifactId>springcloud-model-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Ribbon相关,详情见文档 -->
<!-- eureka客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
修改application.yml 追加eureka的服务注册地址
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
对ConfigBean进行新注解@LoadBalanced 获得Rest时加入Ribbon的配置
主启动类DeptConsumer80_App添加@EnableEurekaClient
修改DeptController_Consumer客户端访问类
先启动3个eureka集群后,再启动springcloud-provider-dept-8001并注册进eureka
启动springcloud-consumer-dept-80
测试
http://localhost/consumer/dept/getById/1
http://localhost/consumer/dept/getAll
小总结: Ribbon和Eureka整合后Consumer可以直接调用服务而不用再关心地址和端口号
Ribbon负载均衡
- 参考springcloud-provider-dept-8001,新建两份,分别命名为8002,8003
- 新建8002/8003数据库,各自微服务分别连各自的数据库
- 修改8002/8003各自YML: 端口/数据库连接
备注:对外暴露的统一服务器实例名:一定不能改
启动3个eureka集群配置区
启动3个Dept微服务启动并各自测试通过
http://localhost:8001/dept/getAll
http://localhost:8002/dept/getAll
http://localhost:8003/dept/getAll
启动springcloud-consumer-dept-80
客户端通过Ribbon完成负载均衡并访问上一步的Dept微服务
总结:Ribbon其实就是一个软负载均衡的客户端组件,
他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。
Ribbon核心组件IRule
Rule:根据特定算法中从服务列表中选取一个要访问的服务
默认自带的7种方法:
RoundRobinRule 轮询
RandomRule 随机
AvailabilityFilteringRule 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问
WeightedResponseTimeRule 根据平时响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到WeightedResponseTimeRule
RetryRule 先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内进行充实,获取可用的服务
BestAvailableRule 会先过滤掉由于多次访问故障而处于熔断器跳闸状态的服务,然后选择一个并发量最小的服务
ZoneAvoidanceRule 默认规则,复合判断server所在区域的性能和server的可用性选择服务器
在ConfigBean.java中
@Bean
public IRule myRule() {
return new RoundRobinRule();//轮询算法
// return new RandomRule();//使用随机算法替代默认的轮询算法
// return new RetryRule();
}
Ribbon自定义
修改springcloud-model-consumer-dept-80
主启动类加@RibbonClient
在启动该微服务的时候就能去加载我们的自定义Ribbon配置类,从而使配置生效,形如:@RibbonClient(name=”SPRINGCLOUD-MODEL-DEPT”,configuration=MySelfRule.class)
注意配置细节
官方文档明确给出了警告:这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是说:我们达不到特殊化定制的目的;而@ComponentScan 就在主启动类的@SpringBootApplication 里面
步骤
- 新建package com.jiangjy.myrule
新建自定义Ribbon的规则类MySelfRule.java
package com.jiangjy.myrule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
@Configuration //配置spring.xml形式的注解
public class MySelfRult {
@Bean //交给容器管理
public IRule myRule() {
return new RandomRule();//Ribbon默认轮询,自定义随机
}
}
修改主启动类
package com.jiangjy.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 com.jiangjy.myrule.MySelfRult;
@SpringBootApplication
@EnableEurekaClient //和eureka整合并使用客户端
//在启动微服务的时候就能去加载我们自定义的Ribbon配置类,从而使配置生效
@RibbonClient(name="SPRINGCLOUD-MODEL-DEPT",configuration=MySelfRult.class)
public class DeptConsumer80_APP {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer80_APP.class, args);
}
}
图解
测试及结果
自定义规则深度解析
问题:在轮询策略的基础上,添加新的需求,每次服务器要求被调用6次,即以前每台机器一次,现在是每台机器6次。
参考源码修改为我们需求需要的RandomRule_Jack.java
package com.jiangjy.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 RandomRule_Jack extends AbstractLoadBalancerRule {
//total = 0 //当total==6以后,我们的指针才往下走
//index = 0 //当前对外提供服务的服务器地址
// total 需要重新置为0,但是达到过一个6次,index = 1
// 分析:我们需要6次,但是微服务只有8001,8002,8003 三台机器
//所以需要我们每读取6次, index加1次,到达三次(三台机器满足条件)
private int total = 0; //总共被调用的次数,目前要求每台被调用6次
private int currentIndex = 0; //当前提供服务的机器号码
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 (total < 6) {
server = upList.get(currentIndex);
total++;
}else {
total = 0;
currentIndex++;
if (currentIndex >= upList.size()) {
currentIndex = 0;
}
}
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;
}
protected int chooseRandomInt(int serverCount) {
return ThreadLocalRandom.current().nextInt(serverCount);
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
// TODO Auto-generated method stub
}
}
调用
package com.jiangjy.myrule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
@Configuration //配置spring.xml形式的注解
public class MySelfRult {
@Bean //交给容器管理
public IRule myRule() {
// return new RandomRule();//Ribbon默认轮询,自定义随机
return new RandomRule_Jack();//自定义每台机器6次
}
}
测试结果: