SpringCloud入门最佳实践(五)Ribbon负载均衡
介绍
是什么
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。
简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load
Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法。
能干嘛
LB,即负载均衡(Load Balance),在微服务或分布式集群中经常用的一种应用。
负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA。 常见的负载均衡有软件Nginx,LVS,硬件 F5等。
相应的在中间件,例如:dubbo和SpringCloud中均给我们提供了负载均衡,SpringCloud的负载均衡算法可以自定义。
集中式LB
即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5, 也可以是软件,如nginx),
由该设施负责把访问请求通过某种策略转发至服务的提供方;
进程内LB
将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。
Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。
官方资料
Ribbon 配置初步
修改 icodecloud-consumer-dept-80 工程
-
POM文件。新增
<!-- Ribbon相关 --> <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>
-
修改YML。追加eureka的服务注册地址
-
对ConfigBean进行新注解@LoadBalanced 获得Rest时加入Ribbon的配置
@Configuration public class ConfigBean { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } }
-
主启动类DeptConsumer80_App添加@EnableEurekaClient
@SpringBootApplication @EnableEurekaClient public class DeptConsumer8000_App { public static void main(String[] args) { SpringApplication.run(DeptConsumer8000_App.class, args); } }
-
设置微服务的真实名字访问
private static final String REST_URL_PREFIX = “http://localhost:8001”;
改为
private static final String REST_URL_PREFIX = “http://ICODECLOUD-DEPT”; -
测试
- 先启动3个eureka集群后,再启动 icodecloud-provider-dept-8001 并注册进 eureka
- 启动 icodecloud-consumer-dept-80
-
总结
Ribbon 和 Eureka 整合后 Consumer 可以直接调用服务而不用再关心地址和端口号
Ribbon 负载均衡
-
架构说明
-
参考 icodecloud-provider-dept-8001,新建两份,分别命名为8002,8003
-
新建8002/8003数据库,各自微服务分别连各自的数据库
-
修改8002/8003各自YML
-
8002 yml
server: port: 8002 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.icode.cloud.pojo # 所有Entity别名类所在包 mapper-locations: - classpath:mybatis/mapper/**/*.xml # mapper映射文件 spring: application: name: icodecloud-dept #对外暴露的微服务名字 datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包 url: jdbc:mysql://localhost:3306/icode-cloud-02 # 数据库名称 username: root password: 123456 dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka: client: #客户端注册进eureka服务列表内 service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: icodecloud-dept8002 prefer-ip-address: true #访问路径可以显示IP地址 info: app.name: icode-icodecloud company.name: www.icode.com build.artifactId: ${project.artifactId} build.version: ${project.version} build.description: ${project.description}
-
8003 yml
server: port: 8003 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.icode.cloud.pojo # 所有Entity别名类所在包 mapper-locations: - classpath:mybatis/mapper/**/*.xml # mapper映射文件 spring: application: name: icodecloud-dept #对外暴露的微服务名字 datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包 url: jdbc:mysql://localhost:3306/icode-cloud-03 # 数据库名称 username: root password: 123456 dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka: client: #客户端注册进eureka服务列表内 service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: icodecloud-dept8003 prefer-ip-address: true #访问路径可以显示IP地址 info: app.name: icode-icodecloud company.name: www.icode.com build.artifactId: ${project.artifactId} build.version: ${project.version} build.description: ${project.description}
-
-
启动3个eureka集群配置区
-
启动3个Dept微服务并各自测试通过
-
启动 icodecloud-consumer-dept-80
-
客户端通过 Ribbo 完成负载均衡并访问上一步的Dept微服务
http://localhost:8000/consumer/dept/list
注意观察看到返回的数据库名字,各不相同,负载均衡实现 -
总结
Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。
Ribbon 核心组件 IRule
IRule:根据特定算法中从服务列表中选取一个要访问的服务。默认采用轮询算法
-
RoundRobinRule
轮询
-
RandomRule
随机
-
AvailabilityFilteringRule
会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阈值的服务,然后对剩余的服务列表按照轮询策略进行访问
-
WeightedResponseTimeRule
根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。
刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到WeightedResponseTimeRule -
RetryRule
先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务
-
BestAvailableRule
会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务
-
ZoneAvoidanceRule
默认规则,复合判断server所在区域的性能和server的可用性选择服务器
覆盖默认轮询算法
消费者 dept 8000
@Configuration
public class ConfigBean {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@Bean
public IRule myRule(){
//覆盖默认的轮询算法为随机算法
return new RandomRule();
}
}
Ribbon 自定义 访问算法
需求:自定义每个机器轮询访问5次
修改 icodecloud-consumer-dept-80 工程
-
主启动类添加 @RibbonClient
在启动该微服务的时候就能去加载我们的自定义Ribbon配置类,从而使配置生效,形如:
@RibbonClient(name=“ICODECLOUD-DEPT”,configuration=MySelfRule.class) -
细节
官方文档明确给出了警告: 这个自定义配置类不能放在@ComponentScan所扫描的当前包下以及子包下,
否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是说 我们达不到特殊化定制的目的了。 -
新建 com.icode.myrule.myrule 包,自定义Robbin规则类
@Configuration public class MySelfRule { @Bean public IRule myRule() { //Ribbon默认是轮询,我自定义为随机 return new RandomRule(); } }
-
修改主启动类,新增刚刚配置的规则类
@RibbonClient(name="ICODECLOUD-DEPT",configuration= MySelfRule.class) @SpringBootApplication @EnableEurekaClient public class DeptConsumer8000_App { public static void main(String[] args) { SpringApplication.run(DeptConsumer8000_App.class, args); } }
-
测试
-
自定义规则解析
问题:依旧轮询策略,但是加上新需求,每个服务器要求被调用5次。 也即以前是每台机器一次,现在是每台机器5次
-
参考源码修改为我们需求要求的RandomRule_XC.java
复制上面对应的源码,改造符合需求的算法
public class RandomRule_XC extends AbstractLoadBalancerRule { //总共被调用的次数,目前要求每台被调用5次 private int total = 0; //当前提供服务的机器号 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 = rand.nextInt(serverCount); // server = upList.get(index); if (total < 5) { 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; } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } }
-
修改 MySelfRule
@Configuration public class MySelfRule { @Bean public IRule myRule() { //Ribbon默认是轮询,我自定义为随机 //return new RandomRule(); //我自定义为每个机器被访问5次 return new RandomRule_XC(); } }
-
修改 主启动类
新增:@RibbonClient(name=“ICODECLOUD-DEPT”,configuration= MySelfRule.class)
-
测试