微服务模块feign,dubbo等服务调用框架在面对调用多个服务器服务时都有实现自己的负载均衡策略。了解每个负载均衡算法有助于我们在使用这些组件时更好的去选择使用哪一种负载均衡策略更符合业务系统运行规则。
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { int length = invokers.size(); int totalWeight = 0; boolean sameWeight = true; // 堆代码 duidaima.com // 下面这个循环有两个作用,第一是计算总权重 totalWeight, // 第二是检测每个服务提供者的权重是否相同 for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); // 累加权重 totalWeight += weight; // 检测当前服务提供者的权重与上一个服务提供者的权重是否相同, // 不相同的话,则将 sameWeight 置为 false。 if (sameWeight && i > 0 && weight != getWeight(invokers.get(i - 1), invocation)) { sameWeight = false; } } // 下面的 if 分支主要用于获取随机数,并计算随机数落在哪个区间上 if (totalWeight > 0 && !sameWeight) { // 随机获取一个 [0, totalWeight) 区间内的数字 int offset = random.nextInt(totalWeight); // 循环让 offset 数减去服务提供者权重值,当 offset 小于0时,返回相应的 Invoker。 // 举例说明一下,我们有 servers = [A, B, C],weights = [5, 3, 2],offset = 7。 // 第一次循环,offset - 5 = 2 > 0,即 offset > 5, // 表明其不会落在服务器 A 对应的区间上。 // 第二次循环,offset - 3 = -1 < 0,即 5 < offset < 8, // 表明其会落在服务器 B 对应的区间上 for (int i = 0; i < length; i++) { // 让随机值 offset 减去权重值 offset -= getWeight(invokers.get(i), invocation); if (offset < 0) { // 返回相应的 Invoker return invokers.get(i); } } } // 如果所有服务提供者权重值相同,此时直接随机返回一个即可 return invokers.get(random.nextInt(length)); }实现步骤
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { int length = invokers.size(); // 最小的活跃数 int leastActive = -1; // 具有相同“最小活跃数”的服务者提供者(以下用 Invoker 代称)数量 int leastCount = 0; // leastIndexs 用于记录具有相同“最小活跃数”的 Invoker 在 invokers 列表中的下标信息 int[] leastIndexs = new int[length]; int totalWeight = 0; // 第一个最小活跃数的 Invoker 权重值,用于与其他具有相同最小活跃数的 Invoker 的权重进行对比, // 以检测是否“所有具有相同最小活跃数的 Invoker 的权重”均相等 int firstWeight = 0; boolean sameWeight = true; // 遍历 invokers 列表 for (int i = 0; i < length; i++) { Invoker<T> invoker = invokers.get(i); // 获取 Invoker 对应的活跃数 int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // 获取权重 - ⭐️ int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); // 发现更小的活跃数,重新开始 if (leastActive == -1 || active < leastActive) { // 使用当前活跃数 active 更新最小活跃数 leastActive leastActive = active; // 更新 leastCount 为 1 leastCount = 1; // 记录当前下标值到 leastIndexs 中 leastIndexs[0] = i; totalWeight = weight; firstWeight = weight; sameWeight = true; // 当前 Invoker 的活跃数 active 与最小活跃数 leastActive 相同 } else if (active == leastActive) { // 在 leastIndexs 中记录下当前 Invoker 在 invokers 集合中的下标 leastIndexs[leastCount++] = i; // 累加权重 totalWeight += weight; // 检测当前 Invoker 的权重与 firstWeight 是否相等, // 不相等则将 sameWeight 置为 false if (sameWeight && i > 0 && weight != firstWeight) { sameWeight = false; } } } // 当只有一个 Invoker 具有最小活跃数,此时直接返回该 Invoker 即可 if (leastCount == 1) { return invokers.get(leastIndexs[0]); } // 有多个 Invoker 具有相同的最小活跃数,但它们之间的权重不同 if (!sameWeight && totalWeight > 0) { // 随机生成一个 [0, totalWeight) 之间的数字 int offsetWeight = random.nextInt(totalWeight); // 循环让随机数减去具有最小活跃数的 Invoker 的权重值, // 当 offset 小于等于0时,返回相应的 Invoker for (int i = 0; i < leastCount; i++) { int leastIndex = leastIndexs[i]; // 获取权重值,并让随机数减去权重值 - ⭐️ offsetWeight -= getWeight(invokers.get(leastIndex), invocation); if (offsetWeight <= 0) return invokers.get(leastIndex); } } // 如果权重相同或权重为0时,随机返回一个 Invoker return invokers.get(leastIndexs[random.nextInt(leastCount)]); }实现步骤
private static final class ConsistentHashSelector<T> { // 使用 TreeMap 存储 Invoker 虚拟节点 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) { this.virtualInvokers = new TreeMap<Long, Invoker<T>>(); this.identityHashCode = identityHashCode; URL url = invokers.get(0).getUrl(); // 获取虚拟节点数,默认为160 this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160); // 获取参与 hash 计算的参数下标值,默认对第一个参数进行 hash 运算 String[] index = Constants.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]); } for (Invoker<T> invoker : invokers) { String address = invoker.getUrl().getAddress(); for (int i = 0; i < replicaNumber / 4; i++) { // 对 address + i 进行 md5 运算,得到一个长度为16的字节数组 byte[] digest = md5(address + i); // 对 digest 部分字节进行4次 hash 运算,得到四个不同的 long 型正整数 for (int h = 0; h < 4; h++) { // h = 0 时,取 digest 中下标为 0 ~ 3 的4个字节进行位运算 // h = 1 时,取 digest 中下标为 4 ~ 7 的4个字节进行位运算 // h = 2, h = 3 时过程同上 long m = hash(digest, h); // 将 hash 到 invoker 的映射关系存储到 virtualInvokers 中, // virtualInvokers 需要提供高效的查询操作,因此选用 TreeMap 作为存储结构 virtualInvokers.put(m, invoker); } } } } } public Invoker<T> select(Invocation invocation) { // 将参数转为 key String key = toKey(invocation.getArguments()); // 对参数 key 进行 md5 运算 byte[] digest = md5(key); // 取 digest 数组的前四个字节进行 hash 运算,再将 hash 值传给 selectForKey 方法, // 寻找合适的 Invoker return selectForKey(hash(digest, 0)); } private Invoker<T> selectForKey(long hash) { // 到 TreeMap 中查找第一个节点值大于或等于当前 hash 的 Invoker Map.Entry<Long, Invoker<T>> entry = virtualInvokers.tailMap(hash, true).firstEntry(); // 如果 hash 大于 Invoker 在圆环上最大的位置,此时 entry = null, // 需要将 TreeMap 的头节点赋值给 entry if (entry == null) { entry = virtualInvokers.firstEntry(); } // 返回 Invoker return entry.getValue(); }实现步骤
public static void main(String[] args) { Map<Integer, String> resMap = new HashMap<>(); for (int i = 0; i < 10; i++) { //Integer widgetId = (int)(Math.random() * 10000); int serverIndex = Hashing.consistentHash(i, 10); if (resMap.containsKey(serverIndex)) { resMap.put(serverIndex, new StringJoiner(",").add(resMap.get(serverIndex)).add(String.valueOf(i)).toString()); } else { resMap.put(serverIndex, String.valueOf(i)); } } resMap.forEach( (k, v) -> System.out.println("group " + k + ": " + v)); }实现步骤
请求编号 | currentWeight 数组 | 选择结果 | 减去权重总和后的 currentWeight 数组 |
---|---|---|---|
1 | [5, 1, 1] | A | [-2, 1, 1] |
2 | [3, 2, 2] | A | [-4, 2, 2] |
3 | [1, 3, 3] | B | [1, -4, 3] |
4 | [6, -3, 4] | A | [-1, -3, 4] |
5 | [4, -2, 5] | C | [4, -2, -2] |
6 | [9, -1, -1] | A | [2, -1, -1] |
7 | [7, 0, 0] | A | [0, 0, 0] |
// 随机一个double值乘以最大权限总和得到一个随机值 double randomWeight = random.nextDouble() * maxTotalWeight; // pick the server index based on the randomIndex int n = 0; // 循环判断随机值在某一个区间,相比如上面的二分查找性能会差一些在很多服务器的情况下 for (Double d : currentWeights) { if (d >= randomWeight) { serverIndex = n; break; } else { n++; } } server = allList.get(serverIndex);实现步骤