欢迎大家关注 github.com/hsfxuebao ,希望对大家有所帮助,要是觉得可以的话麻烦给点一下Star哈
当服务提供方是集群时,为了避免大量请求一直集中在一个或者几个服务提供方机器上,从而使这些机器负载很高,甚至导致服务不可用,需要做 一定的负载均衡策略。 Dubbo 提供了 多种均衡策略,默认为 Random ,也就是每次随机调用一台服务提供者的服务 。
1. 负载均衡的创建和调用
2. 负载均衡的算法
2.1 random
加权随机算法,是 Dubbo 默认的负载均衡算法。权重越大,获取到负载的机率就越大。权重相同,则会随机分配。加权随机算法执行流程示意图:
源码org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance#doSelect:
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
// 若不需要加权负载均衡,则直接生成一个[0, length)的随机数,选择出invoker
if (!needWeightLoadBalance(invokers,invocation)){
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
// Every invoker has the same weight?
boolean sameWeight = true;
// the maxWeight of every invokers, the minWeight = 0 or the maxWeight of the last invoker
// 记录当前invoker及其前面所有invoker的权重之和
int[] weights = new int[length];
// The sum of weights
int totalWeight = 0;
for (int i = 0; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
// Sum
totalWeight += weight;
// save for later use
weights[i] = totalWeight;
if (sameWeight && totalWeight != weight * (i + 1)) {
sameWeight = false;
}
}
// 处理各invoker的权重不同的情况
if (totalWeight > 0 && !sameWeight) {
// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
// 生成一个随机权重[0, totalWeight)
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
// Return a invoker based on the random value.
for (int i = 0; i < length; i++) {
if (offset < weights[i]) {
return invokers.get(i);
}
}
}
// 处理各invoker权重相同的情况(与无权重的处理方式相同)
// If all invokers have the same weight value or totalWeight=0, return evenly.
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
int getWeight(Invoker<?> invoker, Invocation invocation) {
int weight;
URL url = invoker.getUrl();
// Multiple registry scenario, load balance among multiple registries.
// 对于多注册中心的场景,各invoker的权重值就是注册中心的权重
if (REGISTRY_SERVICE_REFERENCE_PATH.equals(url.getServiceInterface())) {
weight = url.getParameter(REGISTRY_KEY + "." + WEIGHT_KEY, DEFAULT_WEIGHT);
} else { // 单注册中心
// 获取weight属性的值
weight = url.getMethodParameter(invocation.getMethodName(), WEIGHT_KEY, DEFAULT_WEIGHT);
if (weight > 0) {
// 获取provider主机的启动时间戳
long timestamp = invoker.getUrl().getParameter(TIMESTAMP_KEY, 0L);
if (timestamp > 0L) {
// 计算当前provider已经启动多久了
long uptime = System.currentTimeMillis() - timestamp;
if (uptime < 0) {
return 1;
}
// 获取warmup(预热)属性值
int warmup = invoker.getUrl().getParameter(WARMUP_KEY, DEFAULT_WARMUP);
if (uptime > 0 && uptime < warmup) {
// 计算预热过程中的权重
weight = calculateWarmupWeight((int)uptime, warmup, weight);
}
}
}
}
return Math.max(weight, 0);
}
2.2 leastactive
加权最小活跃度调度算法。活跃度越小,其优选级就越高,被调度到的机率就越高。活跃度相同,则按照加权随机算法进行负载均衡。
org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance#doSelect:
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
// The least active value of all invokers
int leastActive = -1;
// The number of invokers having the same least active value (leastActive)
int leastCount = 0;
// The index of invokers having the same least active value (leastActive)
int[] leastIndexes = new int[length];
// the weight of every invokers
// 记录每个invoker的权重
int[] weights = new int[length];
// The sum of the warmup weights of all the least active invokers
int totalWeight = 0;
// The weight of the first least active invoker
int firstWeight = 0;
// Every least active invoker has the same weight value?
boolean sameWeight = true;
// Filter out all the least active invokers
// 挑选出具有最小活跃度的所有invoker
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
// Get the active number of the invoker
// 获取当前遍历invoker的最小活跃度,默认为0
int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
// Get the weight of the invoker's configuration. The default value is 100.
int afterWarmup = getWeight(invoker, invocation);
// save for later use
weights[i] = afterWarmup;
// If it is the first invoker or the active number of the invoker is less than the current least active number
if (leastActive == -1 || active < leastActive) {
// Reset the active number of the current invoker to the least active number
leastActive = active;
// Reset the number of least active invokers
leastCount = 1;
// Put the first least active invoker first in leastIndexes
leastIndexes[0] = i;
// Reset totalWeight
totalWeight = afterWarmup;
// Record the weight the first least active invoker
firstWeight = afterWarmup;
// Each invoke has the same weight (only one invoker here)
sameWeight = true;
// If current invoker's active value equals with leaseActive, then accumulating.
} else if (active == leastActive) {
// Record the index of the least active invoker in leastIndexes order
leastIndexes[leastCount++] = i;
// Accumulate the total weight of the least active invoker
totalWeight += afterWarmup;
// If every invoker has the same weight?
if (sameWeight && afterWarmup != firstWeight) {
sameWeight = false;
}
}
} // end-for
// Choose an invoker from all the least active invokers
if (leastCount == 1) {
// If we got exactly one invoker having the least active value, return this invoker directly.
return invokers.get(leastIndexes[0]);
}
// 权重随机算法
if (!sameWeight && totalWeight > 0) {
// If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on
// totalWeight.
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
// Return a invoker based on the random value.
for (int i = 0; i < leastCount; i++) {
int leastIndex = leastIndexes[i];
offsetWeight -= weights[leastIndex];
if (offsetWeight < 0) {
return invokers.get(leastIndex);
}
}
}
// If all invokers have the same weight value or totalWeight=0, return evenly.
return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
}
2.3 shortestresponse
加权最短响应时间算法。从 Invoker 列表中查找平均响应时间最短的作为要选择的Invoker。
org.apache.dubbo.rpc.cluster.loadbalance.ShortestResponseLoadBalance#doSelect:
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers
int length = invokers.size();
// Estimated shortest response time of all invokers
// 记录最短响应时间RT
long shortestResponse = Long.MAX_VALUE;
// The number of invokers having the same estimated shortest response time
int shortestCount = 0;
// The index of invokers having the same estimated shortest response time
int[] shortestIndexes = new int[length];
// the weight of every invokers
// 所有invoker的权重
int[] weights = new int[length];
// The sum of the warmup weights of all the shortest response invokers
int totalWeight = 0;
// The weight of the first shortest response invokers
int firstWeight = 0;
// Every shortest response invoker has the same weight value?
boolean sameWeight = true;
// Filter out all the shortest response invokers
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
// Calculate the estimated response time from the product of active connections and succeeded average elapsed time.
// 获取当前invoker的平均响应时间
long succeededAverageElapsed = rpcStatus.getSucceededAverageElapsed();
// 当前invoker正在处理的活动连接数量
int active = rpcStatus.getActive();
// 计算出当前invoker总的平均响应时间
long estimateResponse = succeededAverageElapsed * active;
int afterWarmup = getWeight(invoker, invocation);
weights[i] = afterWarmup;
// Same as LeastActiveLoadBalance
if (estimateResponse < shortestResponse) {
shortestResponse = estimateResponse;
shortestCount = 1;
shortestIndexes[0] = i;
totalWeight = afterWarmup;
firstWeight = afterWarmup;
sameWeight = true;
} else if (estimateResponse == shortestResponse) {
shortestIndexes[shortestCount++] = i;
totalWeight += afterWarmup;
if (sameWeight && i > 0
&& afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
if (shortestCount == 1) {
return invokers.get(shortestIndexes[0]);
}
if (!sameWeight && totalWeight > 0) {
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < shortestCount; i++) {
int shortestIndex = shortestIndexes[i];
offsetWeight -= weights[shortestIndex];
if (offsetWeight < 0) {
return invokers.get(shortestIndex);
}
}
}
return invokers.get(shortestIndexes[ThreadLocalRandom.current().nextInt(shortestCount)]);
}
2.4 roundrobin
双权重轮询算法,是结合主机权重与轮询权重的、方法级别的轮询算法。执行示意图如下:总权重为28:
org.apache.dubbo.rpc.cluster.loadbalance.AbstractLoadBalance#doSelect:
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// 获取外层map的key
String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
// 获取指定key的所有invoker构成的map,即内层map。
// 若不存在,则创建一个内层map,再放入其中
ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.computeIfAbsent(key, k -> new ConcurrentHashMap<>());
int totalWeight = 0;
// 记录当前最大的轮询权重值
long maxCurrent = Long.MIN_VALUE;
long now = System.currentTimeMillis();
Invoker<T> selectedInvoker = null;
WeightedRoundRobin selectedWRR = null;
// 遍历所有invoker,为它们的轮询权重值增重,并挑选出具有最大轮询权重值的invoker
for (Invoker<T> invoker : invokers) {
// 获取内层map的key
String identifyString = invoker.getUrl().toIdentityString();
// 获取主机权重
int weight = getWeight(invoker, invocation);
// 从缓存map中获取指定key的轮询权重,若不存在,则创建一个轮询权重实例,再放入其中
WeightedRoundRobin weightedRoundRobin = map.computeIfAbsent(identifyString, k -> {
WeightedRoundRobin wrr = new WeightedRoundRobin();
wrr.setWeight(weight);
return wrr;
});
// 只有预热权重会发生变化
if (weight != weightedRoundRobin.getWeight()) {
//weight changed
weightedRoundRobin.setWeight(weight);
}
// 增重
long cur = weightedRoundRobin.increaseCurrent();
// 记录增重时间
weightedRoundRobin.setLastUpdate(now);
// 若当前增重后的轮询权重值大于当前记录的最大的轮询权重值,
// 则修改记录的最大轮询权重值,并将当前invoker记录下来
if (cur > maxCurrent) {
maxCurrent = cur;
selectedInvoker = invoker;
selectedWRR = weightedRoundRobin;
}
// 计算所有invoker的主机权重和
totalWeight += weight;
} // end-for
// 这里的不等,只有一种可能: invokers.size() < map.size(),不可能出现大于的情况
// 小于说明出现了invoker宕机,而大于则是扩容。但扩容后在执行前面的for()时,会使map的size()增加,
// 然后这里的invokers.size()与map.size()就又相等了。
if (invokers.size() != map.size()) {
// map.entrySet() 获取一个set集合,其元素为entry
// removeIf() 的作用是,其参数predicate若为true,则将当前元素删除
// now - item.getValue().getLastUpdate() 计算出的是,距离上次增重已经过去多久了
// predicate条件为,若当前invoker距离上次增重时长已经超过了回收期,则说明当前invoker
// 已经宕机很久了,就可以将其从缓存map中删除了
map.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
}
// 若选择出的invoker不为null,则返回该invoker
if (selectedInvoker != null) {
// 减重
selectedWRR.sel(totalWeight);
return selectedInvoker;
}
// should not happen here
return invokers.get(0);
}
2.5 consistenthash
2.5.1 一致性hash
在分布式系统中解决负载均衡问题的时候可以使用hash算法来将固定的一部分请求落在同一台机器上,这样每台服务器会固定的处理同一部分请求。来起到负载均衡的作用。
但是普通的余数的hash(hash(key)%机器数)算法伸缩性很差,每当新增或者下线机器的时候,某个key与机器的映射会大量的失效,一致性hash则利用hash环对其进行了改进。
我们举个例子,比如我现在有4台服务器,他们对应的ip地址分别是ip1,ip2,ip3,ip4,通过计算这4个ip的hash值(这里假设hash(ip4)> hash(ip3)>hash(ip2)>hash(ip1)),然后按照hash值的大小顺时针分布到hash环上:
我们可以看到,从0开始然后按照4个ip的hash值大小顺时针方向(这个趋向正无穷大)散落在环上(这里假设hash(ip4)> hash(ip3)>hash(ip2)>hash(ip1)),当用户调用请求打过来的时候,计算用户某个参数的hash(key)值,比如说我们 用户u1的key的hash值正好在hash(ip3)值 与hash(2) 值之间,如下图:
这时候u1的请求就要交给hash(ip3)也就是ip3的这台机器处理。当我们ip3的机器挂了的时候,我们的hash环是这样分布的:
这时候u1这个请求就会被重新分配到ip4的机器上,之前不分配到ip3机器上的用户请求不受影响。我们回到ip3没有挂之前,我们新添加了ip5的机器,hash(ip5)值正好在hash(ip2)与hash(ip3)之间。在环上的图如下:
这时候ip5的机器会分担一部分ip3机器的请求, 如果hash(u1.key)值 在ip5 与ip2 之前,这时候u1的请求就会被重新分配到ip5机器上处理。
当我们机器比较的少时候会造成数据倾斜的问题,就是可能会出现大量的请求被分配到一台机器上情况。这时候可以使用虚拟节点来解决数据倾斜问题,我们给每台机器添加多个虚拟节点,我们来看下dubbo对于一致性hash的落地。(关于更多一致性hash原理问题可以参考《深入浅出一致性Hash原理》这篇文章)
2.5.2 dubbo的一致性哈希算法
一致性 hash 算法。其是一个方法参数级别的负载均衡。对于同一调用方法的、相同实参的、远程调用请求,其会被路由到相同的 invoker。其是以调用方法的指定实参的 hash 值为 key 进行 invoker 选择的。执行示意图如下:
public interface GreetingService {
String hello(String name, String value, int age);
}
配置文件中:
<dubbo:reference version="1.0.0" group="greeting" id="greetingService" check="false"
interface="org.apache.dubbo.demo.GreetingService" >
<dubbo:method name="hello" >
<dubbo:parameter key="hash.arguments" value="0,1"/> // 表示实参拼接后计算hash值
<dubbo:parameter key="hash.nodes" value="160"/>/
</dubbo:method>
</dubbo:reference>
源码org.apache.dubbo.rpc.cluster.loadbalance.ConsistentHashLoadBalance#doSelect:
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// 获取RPC调用的全限定性方法名
String methodName = RpcUtils.getMethodName(invocation);
// 计算一致性hash选择器的key
String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
// using the hashcode of list to compute the hash only pay attention to the elements in the list
int invokersHashCode = invokers.hashCode();
// selectors是一个缓存map,其key为前面的key,value为一致性hash选择器
// 获取当前调用方法对应的选择器
ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
// 若选择器为空,则创建一个
if (selector == null || selector.identityHashCode != invokersHashCode) {
// 创建选择器后,再写入到缓存map
selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, invokersHashCode));
selector = (ConsistentHashSelector<T>) selectors.get(key);
}
// 进行一致性hash选择
return selector.select(invocation);
}
如上,doSelect 方法主要做了一些前置工作,比如检测 invokers 列表是不是变动过,以及创建 ConsistentHashSelector。这些工作做完后,接下来开始调用 ConsistentHashSelector 的 select 方法执行负载均衡逻辑。在分析 select 方法之前,我们先来看一下一致性 hash 选择器 ConsistentHashSelector 的初始化过程,如下:
private static final class ConsistentHashSelector<T> {
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
// 一个map,其key为虚拟invoker的hash,value为物理invoker
this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
this.identityHashCode = identityHashCode;
URL url = invokers.get(0).getUrl();
// 获取hash.nodes属性值,即要创建的虚拟invoker的数量,即副本数量
this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
// 获取hash.arguments属性值,并使用逗号进行分隔
String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0"));
// 将分隔出的参数索引变为整型后写入到数组
argumentIndex = new int[index.length];
for (int i = 0; i < index.length; i++) {
argumentIndex[i] = Integer.parseInt(index[i]);
}
// 遍历所有物理invoker,为它们创建相应的虚拟invoker
for (Invoker<T> invoker : invokers) {
String address = invoker.getUrl().getAddress();
for (int i = 0; i < replicaNumber / 4; i++) {
// 使用md5算法生成一个128位(16字节)的摘要
byte[] digest = Bytes.getMD5(address + i);
// 一个hash由32位二进制数生成,所以一个摘要可以生成4个hash。
for (int h = 0; h < 4; h++) {
// 每32位二进制数生成一个hash
long m = hash(digest, h);
// 每个hash将作为一个虚拟invoker,即map的key
virtualInvokers.put(m, invoker);
}
}
}
}
}
ConsistentHashSelector 的构造方法执行了一系列的初始化逻辑,比如从配置中获取虚拟节点数以及参与 hash 计算的参数下标,默认情况下只使用第一个参数进行 hash。需要特别说明的是,ConsistentHashLoadBalance 的负载均衡逻辑只受参数值影响,具有相同参数值的请求将会被分配给同一个服务提供者。ConsistentHashLoadBalance 不 关系权重,因此使用时需要注意一下。
在获取虚拟节点数和参数下标配置后,接下来要做的事情是计算虚拟节点 hash 值,并将虚拟节点存储到 TreeMap 中。到此,ConsistentHashSelector 初始化工作就完成了。接下来,我们来看看 select 方法的逻辑。
public Invoker<T> select(Invocation invocation) {
// 将数组元素代表的索引的实参值进行字符串拼接
String key = toKey(invocation.getArguments());
// 使用key生成一个摘要
byte[] digest = Bytes.getMD5(key);
// 取摘要的前32位生成一个hash,使用该hash进行选择
return selectForKey(hash(digest, 0));
}
private String toKey(Object[] args) {
StringBuilder buf = new StringBuilder();
// 遍历数组,将该数组元素代表的索引的实参值进行字符串拼接
for (int i : argumentIndex) {
if (i >= 0 && i < args.length) {
buf.append(args[i]);
}
}
return buf.toString();
}
private Invoker<T> selectForKey(long hash) {
// 选择一个比当前hash值大的最小的一个缓存map的key对应的entry
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
if (entry == null) {
entry = virtualInvokers.firstEntry();
}
// 获取entry中的物理invoker
return entry.getValue();
}
private long hash(byte[] digest, int number) {
return (((long) (digest[3 + number * 4] & 0xFF) << 24)
| ((long) (digest[2 + number * 4] & 0xFF) << 16)
| ((long) (digest[1 + number * 4] & 0xFF) << 8)
| (digest[number * 4] & 0xFF))
& 0xFFFFFFFFL;
}
如上,选择的过程相对比较简单了。首先是对参数进行 md5 以及 hash 运算,得到一个 hash 值。然后再拿这个值到 TreeMap 中查找目标 Invoker 即可。
到此关于 ConsistentHashLoadBalance 就分析完了。
在阅读ConsistentHashLoadBalance 源码之前,建议读者先补充背景知识,不然看懂代码逻辑会有很大难度。