六、SpringCloud 微服务之 Ribbon 负载均衡服务调用
Ribbon 负载均衡服务调用
1. 概述
1.1 Ribbon 是什么
Spring Cloud Ribbon 是基于 Netfix Ribbon 实现的一套客户端负载均衡工具。 Ribbon 是 Netfix 发布的开源项目,主要功能就是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项,如:连接超时、重试等。在配置文件中列出 Load Balancer(简称LB)后面所有的机器,Ribbon 会自动帮助你基于某种规则(如简单轮询、随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
1.2 官网资料
Ribbon 目前也进入了维护模式 未来替换方案,是Spring Cloud自己开发的 SpringCloud loadBalancer
1.3 能干什么
1. LB(负载均衡)
将用户请求平摊分配到多个服务上,从而达到系统的HA(高可用)。常见的负载均衡软件有:Nginx、LVS、硬件F5等
进程内LB 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。 Ribbon就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址;
2. Ribbon负载均衡演示
2.1 架构说明
Ribbon在工作时分成两步 先选择EurekaServer,它优先选择在同一个区域内负载较少的server 再根据用户指定的策略,然后从server渠道服务注册列表中选择一个地址 Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权
总结: Ribbon其实就是一个软负载均衡的客户端组件, 他可以和其他所需请求的客户端结合使用,和eureka结合只是其中一个实例.
2.2 pom
可以看到 spring-cloud-starter-netflix-eureka-client 包中已经包含了 Ribbon 相关的依赖
2.3 RestTemplate 的使用
@RestController @Slf4j public class OrderController { //private static final String PAYMENT_URL = "http://localhost:8001"; private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE"; private final RestTemplate restTemplate; @Autowired public OrderController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * 返回对象为响应实体中数据转换成的对象,基本上可以理解为JSON * @param payment * @return */ @GetMapping("/consumer/payment/create") public CommonResult<Payment> create(Payment payment) { log.info("payment = {}", JSON.toJSONString(payment)); return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class); } @GetMapping("/consumer/payment/get/{id}") public CommonResult<Payment> getPayment(@PathVariable("id") Long id) { return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class); } @GetMapping("/consumer/payment/getEntity/{id}") public CommonResult<Payment> getPayment2(@PathVariable("id") Long id) { ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class); if (forEntity.getStatusCode().is2xxSuccessful()) { log.info("{} {} {}", forEntity.getStatusCode(), forEntity.getHeaders(), forEntity.getBody()); return forEntity.getBody(); } return new CommonResult<>(444, "操作失败"); } /** * 返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如:响应头、响应状态码、响应体等 * @param payment * @return */ @GetMapping("/consumer/payment/createEntity") public CommonResult<Payment> create2(Payment payment) { ResponseEntity<CommonResult> postForEntity = restTemplate.postForEntity( PAYMENT_URL + "/payment/create", payment, CommonResult.class); if (postForEntity.getStatusCode().is2xxSuccessful()){ log.info("{} {} {}", postForEntity.getStatusCode(), postForEntity.getHeaders(), postForEntity.getBody()); return postForEntity.getBody(); } return new CommonResult<>(444, "操作失败"); } }
3. Ribbon核心组件IRule
IRule:根据特定算法从服务列表中选取一个要访问的服务 com.netflix.loadbalancer.RoundRobinRule 轮询 com.netflix.loadbalancer.RandomRule 随机 com.netflix.loadbalancer.RetryRule 先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内进行重试,获取可用的服务 com.netflix.loadbalancer.WeightedResponseTimeRule 对RoundRobinRule的扩展,响应速度越快的实例选择权重越多大,越容易被选择 com.netflix.loadbalancer.BestAvailableRule 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务 com.netflix.loadbalancer.AvailabilityFilteringRule 先过滤掉故障实例,再选择并发较小的实例 com.netflix.loadbalancer.ZoneAvoidanceRule 默认规则,复合判断server所在区域的性能和server的可用性选择服务器
如何替换?
修改cloud-consumer-order80 注意配置细节 官方文档明确给出了警告: 这个自定义配置类不能放在 @ComponentScan 所扫描的当前包以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,达不到特殊化定制的目的
在com.zzx下新建 springcloud 的同级包 rule 新建 MySelfRule 规则类
package com.zzx.rule; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description: 自定义负载均衡路由规则类 */ @Configuration public class MySelfRule { /** * 定义规则为随机 * @return */ @Bean public IRule getRule(){ return new RandomRule(); } }
在主启动类上添加 @RibbonClient 注解
package com.zzx.springcloud; import com.zzx.rule.MySelfRule; 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; @SpringBootApplication @EnableEurekaClient @RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class) public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args); } }
使用 chrome 测试 通过后台日志发现是随机访问的8001和8002两个微服务
4. Ribbon负载均衡算法
原理 负载均衡算法:rest接口第几次请求数%服务器集群总数量=实际调用服务器位置下标,每次服务重启后rest接口计数从1开始 eg: List[0] instances = 127.0.0.1:8002 List[0] instances = 127.0.0.1:8001 8001+8002组成集群,他们共计两台机器,集群总数为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 如此类推…
源码
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package com.netflix.loadbalancer; import com.netflix.client.config.IClientConfig; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RoundRobinRule extends AbstractLoadBalancerRule { private AtomicInteger nextServerCyclicCounter; private static final boolean AVAILABLE_ONLY_SERVERS = true; private static final boolean ALL_SERVERS = false; private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class); // 初始化循环计数器 nextServerCyclicCounter,初始值为0 public RoundRobinRule() { this.nextServerCyclicCounter = new AtomicInteger(0); } public RoundRobinRule(ILoadBalancer lb) { this(); this.setLoadBalancer(lb); } public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } else { Server server = null; int count = 0; while(true) { // count 为最大重试次数 if (server == null && count++ < 10) { // 获取存活的服务 List<Server> reachableServers = lb.getReachableServers(); // 获取所有的服务 List<Server> allServers = lb.getAllServers(); int upCount = reachableServers.size(); int serverCount = allServers.size(); if (upCount != 0 && serverCount != 0) { // 对服务器取模获取下一个服务器索引 int nextServerIndex = this.incrementAndGetModulo(serverCount); // 根据服务器索引获取服务 server = (Server)allServers.get(nextServerIndex); /** * 判断当前服务是否为null,如果为null * 让当前线程由“运行状态”进入到“就绪状态”,从而让其它具有相同优先级的等待线程获取执行权;但是,并不能保 * 证在当前线程调用yield()之后,其它具有相同优先级的线程就一定能获得执行权; * 也有可能是当前线程又进入到“运行状态”继续运行! */ if (server == null) { Thread.yield(); } else { // 如果不为null,判断服务是否存活,并准备好服务,如果是,返回该服务 // 否则,将服务置为null,并进行下一次循环 if (server.isAlive() && server.isReadyToServe()) { return server; } server = null; } continue; } log.warn("No up servers available from load balancer: " + lb); return null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; } } } // 对 nextServerCyclicCounter 进行自增,并根据服务器数量取模 private int incrementAndGetModulo(int modulo) { int current; int next; do { current = this.nextServerCyclicCounter.get(); next = (current + 1) % modulo; } while(!this.nextServerCyclicCounter.compareAndSet(current, next)); return next; } public Server choose(Object key) { return this.choose(this.getLoadBalancer(), key); } public void initWithNiwsConfig(IClientConfig clientConfig) { } }
上一篇:
多线程四大经典案例
下一篇:
MYSQL完全手册学习笔记(第九章)