文章目录
入门介绍
Ribbon概述
Spring Cloud Ribbon是基于Netflix Ribbon软件开发定制定制实现的一套客户端 软件开发定制定制负载均衡的工具。
Ribbon是Netflix软件开发定制定制发布的开源项目,软件开发定制定制主要功能是提供客户端软件开发定制定制的软件负载均衡算法和服务调用。Ribbon软件开发定制定制客户端组件提供一系列软件开发定制定制完善的配置项如连接超时,重试等。
简单的说,软件开发定制定制就是在配置文件中列出Load Balancer(简称LB)软件开发定制定制后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单,随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高可用)。
常见的负载均衡有软件Nginx,LVS,硬件F5等。
负载均衡器组件
- 一个负载均衡器,至少提供以下功能:
- 要维护各个服务器的IP等信息
- 根据特定逻辑选取服务器
- 为了实现基本的负载均衡功能,Ribbon的负载均衡器有三大子模块:
- Rule:负载均衡规则
- Ping:心跳检测
- ServerList:需要再ribbon保存完整服务器IP集合,只有知道了信息集合才能知道如何使用Rule
Ribbon实现负载均衡原理
LoadBalancerClient
LoadBalancerClient是负载均衡器的核心类,它可以通过eureka- client获取到负载均衡服务提供者的实例信息,并将服务注册列表信息缓存一份,从而实现了客户端的负载均衡。
Ribbon的负载均衡主要是通过LoadBalancerClient来实现的,而 LoadBalancerClient具体交给了ILoadBalancer来处理,ILoadBalancer通过配置IRule,IPing等,向Eureka Client获取注册列表信息,默认每10秒向Eureka Client发送一次「ping」 ,进而检查是否需要更新服务的注册列表信息。最后,在得到服务注册列表信息后,ILoadBalancer根据IRule的策略进行负载均衡。
RestTemplate增加@LoadBalance注解后,在进行远程调度时能够做到负载均衡,主要是维护了一个被@LoadBalance注解的 列表,并给该列表中的RestTemplate对象添加了拦 截器。在拦截器方法中,将远程调度方法交给了 Ribbon的负载均衡器LoadBalancerClient去处理,从而实现了负载均衡的目的。
Ribbon的负载均衡和RestTemplate调用
Ribbon其实就是一个软负载均衡的客户端组件,它可以和其他所需请求的客户端结合使用,和Eureka结合只是其中的一个实例。
Ribbon在工作时分成两步:
第一步先选择EurekaServer ,它优先选择在同一个区域内负载较少的server。
第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址。
其中Ribbon提供了多种策略:比如轮询、随机和根据响应时间加权。
Ribbon依赖
先前工程项目没有引入spring-cloud-starter-netflix-ribbon也可以使用ribbon。
<dependency> <groupld>org.springframework.cloud</groupld> <artifactld>spring-cloud-starter-netflix-ribbon</artifactid></dependency>
- 1
- 2
- 3
- 4
这是因为spring-cloud-starter-netflix-eureka-client自带了spring-cloud-starter-netflix-ribbon引用。
RestTemplate使用说明
官方文档:
getForObject() / getForEntity() - GET请求方法
getForObject():返回对象为响应体中数据转化成的对象,基本上可以理解为json。
getForEntity():返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等。
@GetMapping("/consumer/getForEntity/{id}")public RestResult<UserTest> getUser(@PathVariable("id") Long id){ ResponseEntity<RestResult> entity = restTemplate.getForEntity(BASE_URL + "/get/" + id, RestResult.class); // is2xxSuccessful 成功状态 if(entity.getStatusCode().is2xxSuccessful()){ return entity.getBody();//getForObject() }else{ return RestResult.fail(ResultCode.DATA_ACCESS_ERROR); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
postForObject() / postForEntity() - POST请求方法
Ribbon默认自带的负载规则
lRule:根据特定算法中从服务列表中选取一个要访问的服务
- RoundRobinRule 轮询。
- RandomRule 随机。
- RetryRule 先按照RoundRobinRule的策略获取服务,如果获取服务失败则在指定时间内会进行重试,获取可用的服务。
- WeightedResponseTimeRule 对RoundRobinRule的扩展,响应速度越快的实例选择权重越大,越容易被选择。
- BestAvailableRule 会先过滤掉由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务。
- AvailabilityFilteringRule 先过滤掉故障实例,再选择并发较小的实例。
- ZoneAvoidanceRule 默认规则,复合判断server所在区域的性能和server的可用性选择服务器。
Ribbon负载规则替换
1.修改cloud-consumer-80
2.新建配置类
@Configurationpublic class MySelfRule { @Bean public IRule myRule() { return new RandomRule(); // 随机 }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
主启动类添加@RibbonClient
@SpringBootApplication@EnableEurekaClient@RibbonClient(name = "cloud-provider-service", configuration = MySelfRule.class)public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class,args); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
然后访问cloud-provider-service服务就是随机的。
Ribbon默认负载轮询算法原理
默认负载轮训算法: rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标,每次服务重启动后rest接口计数从1开始。
有俩台机器
- 127.0.0.1:8002
- 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
- 如此类推…
RoundRobinRule源码分析
package com.netflix.loadbalancer;import com.netflix.client.config.IClientConfig;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.List;import java.util.concurrent.atomic.AtomicInteger;/** * The most well known and basic load balancing strategy, i.e. Round Robin Rule. * * @author stonse * @author Nikos Michalakis <nikos@netflix.com> * */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); public RoundRobinRule() { nextServerCyclicCounter = new AtomicInteger(0); } public RoundRobinRule(ILoadBalancer lb) { this(); setLoadBalancer(lb); } // 重点关注这方法。 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) { // 只有已启动且可访问的服务器。 List<Server> reachableServers = lb.getReachableServers(); // 所有已知的服务器,包括可访问和不可访问的服务器。 List<Server> allServers = lb.getAllServers(); int upCount = reachableServers.size(); int serverCount = allServers.size(); 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; } /** * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}. * * @param modulo The modulo to bound the value of the counter. * @return The next value. */ private int incrementAndGetModulo(int modulo) { for (;;) { int current = nextServerCyclicCounter.get(); int next = (current + 1) % modulo;// 求余法 // CAS 比较并交换 if (nextServerCyclicCounter.compareAndSet(current, next)) return next; } } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
Ribbon之手写轮询算法
public interface LoadBalancer { /** * 轮训获取服务 * @param serviceInstances * @return */ ServiceInstance instances(List<ServiceInstance> serviceInstances);}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
@Servicepublic class MyLb implements LoadBalancer { private AtomicInteger atomicInteger = new AtomicInteger(0); /** * 轮训获取服务 * 负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 ,每次服务重启动后rest接口计数从1开始。 * @param serviceInstances * @return */ @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index = getAndIncrement() % serviceInstances.size(); return serviceInstances.get(index); } // 第几次访问 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; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36