Dubbo源码学习16

Dubbo 提供了4种负载均衡实现,分别是基于权重随机算法的 RandomLoadBalance、基于最少活跃调用数算法的 LeastActiveLoadBalance、基于 hash 一致性的 ConsistentHashLoadBalance,以及基于加权轮询算法的 RoundRobinLoadBalance。

不难看出所有负载均衡类均继承自AbstractLoadBalance,AbstractLoadBalance实现了LoadBalance接口,实现了负载均衡的一些公共逻辑。

AbstractLoadBalance.select(List<Invoker<T>> invokers, URL url, Invocation invocation)

@Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        if (invokers == null || invokers.isEmpty())
            return null;
        if (invokers.size() == 1)
            return invokers.get(0);
        //委托子类实现doSelect方法
        return doSelect(invokers, url, invocation);
    }

负载均衡的入口方法,逻辑无需多说,通过子类实现模板方法doSelect方法实现负载均衡逻辑

AbstractLoadBalance.getWeight(Invoker<?> invoker, Invocation invocation)

protected int getWeight(Invoker<?> invoker, Invocation invocation) {
        // 获取提供者url中的weigth权重
        int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
        if (weight > 0) {
            //获取服务提供者启动时间戳remote.timestamp 默认为0L
            long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
            if (timestamp > 0L) {
                //计算服务提供者运行时长
                int uptime = (int) (System.currentTimeMillis() - timestamp);
                //获取服务预热时间warmup 默认为10分钟
                int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
                //如果运行时间小于预热时间,则重新计算服务权重,即降权
                if (uptime > 0 && uptime < warmup) {
                    weight = calculateWarmupWeight(uptime, warmup, weight);
                }
            }
        }
        return weight;
    }

static int calculateWarmupWeight(int uptime, int warmup, int weight) {
        //计算权重,下面代码逻辑上形似于(uptime/warmup)*weight,启动时间/预热时长  然后乘以权重
        int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
        //随着服务运行时间uptime,权重计算值ww会慢慢接近配置weight
        return ww < 1 ? 1 : (ww > weight ? weight : ww);
    }

该方法首先获取权重,如果配置了权重,那么根据启动时间配置和预热时间重新计算权重。这样子做保证当服务运行时长小于服务预热时间时,对服务进行降权,避免让服务在启动之初就处于高负载状态。

RandomLoadBalance

RandLoadBalance是加权随机算法的试下,它的算法思想很简单。假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [5, 3, 2],权重总和为10。现在把这些权重值平铺在一维坐标值上,[0, 5) 区间属于服务器 A,[5, 8) 区间属于服务器 B,[8, 10) 区间属于服务器 C。接下来通过随机数生成器生成一个范围在 [0, 10) 之间的随机数,然后计算这个随机数会落到哪个区间上。比如数字3会落到服务器 A 对应的区间上,此时返回服务器 A 即可。权重越大的机器,在坐标轴上对应的区间范围就越大,因此随机数生成器生成的数字就会有更大的概率落到此区间内。只要随机数生成器产生的随机数分布性很好,在经过多次选择后,每个服务器被选中的次数比例接近其权重比例。比如,经过一万次选择后,服务器 A 被选中的次数大约为5000次,服务器 B 被选中的次数约为3000次,服务器 C 被选中的次数约为2000次。

public class RandomLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "random";

    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //invokers的数量
        int length = invokers.size();
        //权重总数
        int totalWeight = 0;
        //每个Invoker有相同的权重
        boolean sameWeight = true;
        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;
            }
        }
        //如果总权重大于0并且所有权重并不相同
        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 -= getWeight(invokers.get(i), invocation);
                if (offset < 0) {
                    return invokers.get(i);
                }
            }
        }
        //如果所有服务提供者权重值相同,此时直接随机返回一个即可
        return invokers.get(random.nextInt(length));
    }

}

计算总权重totalWeight,如果都没有配置权重或者配置了权重但是invoker的权重都一样,从invokers中随机获取下标在[0,invokers.size)之间的随机数就行了。否则根据总权重生成一个随机数范围[0,totalWeight)的数值offset,遍历invokers列表,使用offset减去每个invoker的权重直到offset小于0则返回当前的invoker。

LeastActiveLoadBalance

最小活跃数负载。活跃调用数越小,表明该提供者效率越高,单位时间内能够处理更多的请求。此时应优先将请求分配给该提供者。再具体实现中,每个服务提供者对应一个活跃数active。初始情况下,所有服务提供者活跃数均为0。每收到一个请求,活跃数加1,完成请求后则将活跃数减1。在服务运行一段时间后,性能好的服务提供者处理请求速度更快,因此活跃数下降的也越快,此时这样的服务提供者能够优先获取到新的服务请求、这就是最小活跃数负载均衡算法的基本思想。除了最小活跃数,LeastActiveLoadBalance 在实现上还引入了权重值。所以准确的来说,LeastActiveLoadBalance 是基于加权最小活跃数算法实现的。举个例子说明一下,在一个服务提供者集群中,有两个性能优异的服务提供者。某一时刻它们的活跃数相同,此时 Dubbo 会根据它们的权重去分配请求,权重越大,获取到新请求的概率就越大。如果两个服务提供者权重相同,此时随机选择一个即可。

public class LeastActiveLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "leastactive";

    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //invokers数量
        int length = invokers.size();
        //最小活跃数
        int leastActive = -1;
        //具有最小活跃数的服务提供者(invoker)的数量
        int leastCount = 0;
        // leastIndexs 用于记录具有相同“最小活跃数”的 Invoker 在 invokers 列表中的下标信息
        int[] leastIndexs = new int[length];
        //预热权重的总和
        int totalWeight = 0;
        //初始值,用于比较
        int firstWeight = 0;
        //每个调用者都具有相同的权重值?
        boolean sameWeight = true;
        for (int i = 0; i < length; i++) {
            Invoker<T> invoker = invokers.get(i);
            //获取 Invoker 对应的活跃数
            int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
            //权重
            int afterWarmup = getWeight(invoker, invocation);
            //发现更小的活跃数,重新开始
            if (leastActive == -1 || active < leastActive) {
                //使用当前活跃数更新leastActive
                leastActive = active;
                //更新 leastCount 为 1
                leastCount = 1;
                //记录下标到leastIndex
                leastIndexs[0] = i;
                //totalWeight权重赋值
                totalWeight = afterWarmup;
                //记录第一个调用者的权重
                firstWeight = afterWarmup;
                //重置,每个调用者都具有相同的权重值?
                sameWeight = true;
                //当前 Invoker 的活跃数 active 与最小活跃数 leastActive 相同
            } else if (active == leastActive) {
                //在 leastIndexs 中记录下当前 Invoker 在 invokers 集合中的下标
                leastIndexs[leastCount++] = i;
                //累加权重
                totalWeight += afterWarmup;
                //检测当前 Invoker 的权重与 firstWeight 是否相等,
                //不相等则将 sameWeight 置为 false
                if (sameWeight && i > 0
                        && afterWarmup != firstWeight) {
                    sameWeight = false;
                }
            }
        }
        // 断言(leastCount> 0)
        if (leastCount == 1) {
            // 如果我们恰好有一个具有最小活动值的调用程序,则直接返回此调用程序。
            return invokers.get(leastIndexs[0]);
        }
        //有多个 Invoker 具有相同的最小活跃数,但它们之间的权重不同
        if (!sameWeight && totalWeight > 0) {
            // 如果(并非每个调用者都具有相同的权重且至少一个调用者的权重大于0),请根据totalWeight随机选择。
            int offsetWeight = random.nextInt(totalWeight) + 1;
            //循环让随机数减去具有最小活跃数的 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时,则从leastIndexes中返回一个 Invoker
        return invokers.get(leastIndexs[random.nextInt(leastCount)]);
    }
}
  • 1.首先找到最小active的下标数组、以及这些active最小的invoker的总权重、和数量、权重是否相同 变量保存起来
  • 2.如果active最小的invoker只有一个,根据active记录的下标数组,取出下标得到invokers即可
  • 3.如果active最小的Invoker有相同的权重或者没配置权重,从记录最小active下标的数组中随机取一个下标,然后从invokers列表中找到这个下标对应的invoker返回
  • 4.如果这些最小active的invoker权重存在,那么我们根据权重找到最小下标数组的下标,然后invokers列表去该下标的元素即可。这一步算法类似RandomLoadBalance

RoundRobinLoadBalance

原理

请求编号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]

[A,B,C]服务器的初始化权重分别为[5,1,1],总权重为7。

  • step1.[A,B,C]的当前权重currentWeight即为初始化权重[5,1,1],选取权重最大的A服务器,将A的当前权重减去总权重作作为A的当前权重值,B,C保持不变,所以currentWeight为[-2,1,1]
  • step2.将currentWeight[-2,1,1]权重分别加上各自的初始化权重[5,1,1],得到currentWeight[3,2,2],此时还是A的权重最大,将A的当前权重减去总权重作作为A的当前权重值,B,C的currentWeight保持不变,所以currentWeight[-4,2,2]
  • step3.将currentWeight[-4,2,2]权重分别加上各自的初始化权重[5,1,1],得到currentWeight[1,3,3],此时B的权重是最大权重为3,把B的权重减去总权重3-7=-4作为B的d当前权重,A,C,所以currentWeight[1,-4,3]
  • step4.将currentWeight[1,-4,3]权重分别加上各自的初始化权重[5,1,1],得到currentWeight[6,-3,4],A权重最大,将A的当前权重减去总权重作为A的当前权重,B,C不变,得到currentWeight[-1,-3,4]
  • step5.将currentWeight[-1,-3,4]权重分别加上各自的初始化权重[5,1,1],得到currentWeight[4,-2,5],C的权重最大,将C的当前权重减去总权重作为C的当前权重,A,B不变,得到currentWeight[4,-2,-2]
  • step6.将currentWeight[4,-2,-2]权重分别加上各自的初始化权重[5,1,1],得到[9, -1, -1],A的权重最大,将A的当前权重减去总权重作为A的当前权重,B,C不变,得到currentWeight[2,-1,-1]
  • step7.将currentWeight[2,-1,-1]权重分别加上各自的初始化权重[5,1,1],得到[7, 0, 0],A的权重最大,将A的当前权重减去总权重作为A的当前权重,B,C不变,得到currentWeight[0,0,0]此时结束
  • step8.最终得到的服务器序列为[A, A, B, A, C, A, A]

如果能够弄明白上述逻辑,那么RoundRobinLoadBalance的代码实现理解起来也就没什么难度了。

public class RoundRobinLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "roundrobin";
    
    private static int RECYCLE_PERIOD = 60000;
    
    protected static class WeightedRoundRobin {
        /**
         * 服务提供者权重
         */
        private int weight;
        /**
         * 当前权重
         */
        private AtomicLong current = new AtomicLong(0);
        /**
         * 最后一次更新时间
         */
        private long lastUpdate;
        public int getWeight() {
            return weight;
        }

        /**
         * 重置权重的同时重置current的属性值
         * @param weight
         */
        public void setWeight(int weight) {
            this.weight = weight;
            current.set(0);
        }
        public long increaseCurrent() {
            // current = current + weight;
            return current.addAndGet(weight);
        }
        public void sel(int total) {
            // current = current - total;
            current.addAndGet(-1 * total);
        }
        public long getLastUpdate() {
            return lastUpdate;
        }
        public void setLastUpdate(long lastUpdate) {
            this.lastUpdate = lastUpdate;
        }
    }

    /**
     *     // 嵌套 Map 结构,存储的数据结构示例如下:
     *     // {
     *     //     "UserService.query": {
     *     //         "url1": WeightedRoundRobin@123,
     *     //         "url2": WeightedRoundRobin@456,
     *     //     },
     *     //     "UserService.update": {
     *     //         "url1": WeightedRoundRobin@123,
     *     //         "url2": WeightedRoundRobin@456,
     *     //     }
     *     // }
     *     // 最外层为服务类名 + 方法名,第二层为 url 到 WeightedRoundRobin 的映射关系。
     *     // 这里我们可以将 url 看成是服务提供者的 id
     */
    private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
    /**
     * 原子更新锁
     */
    private AtomicBoolean updateLock = new AtomicBoolean();
    
    /**
     * get invoker addr list cached for specified invocation
     * <p>
     * <b>for unit test only</b>
     * 
     * @param invokers
     * @param invocation
     * @return
     */
    protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) {
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        Map<String, WeightedRoundRobin> map = methodWeightMap.get(key);
        if (map != null) {
            return map.keySet();
        }
        return null;
    }
    
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //获取group/interface:version.methodName组成的字符串作为key
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        // 获取 url 到 WeightedRoundRobin 映射表,如果为空,则创建一个新的
        ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
        if (map == null) {
            methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
            map = methodWeightMap.get(key);
        }
        int totalWeight = 0;
        long maxCurrent = Long.MIN_VALUE;
        //当前时间
        long now = System.currentTimeMillis();
        Invoker<T> selectedInvoker = null;
        WeightedRoundRobin selectedWRR = null;
        //遍历invokers列表
        for (Invoker<T> invoker : invokers) {
            //提供者url
            String identifyString = invoker.getUrl().toIdentityString();
            //获取WeightedRoundRobin对象
            WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
            //获取当前invoker的权重值
            int weight = getWeight(invoker, invocation);
            if (weight < 0) {
                weight = 0;
            }
            //检测当前Invoker是否有对应的WeightedRoundRobin,没有创建并维护到Map中
            if (weightedRoundRobin == null) {
                weightedRoundRobin = new WeightedRoundRobin();
                //设置权重
                weightedRoundRobin.setWeight(weight);
                //存储 url 唯一标识 identifyString 到 weightedRoundRobin 的映射关系
                map.putIfAbsent(identifyString, weightedRoundRobin);
                weightedRoundRobin = map.get(identifyString);
            }
            // Invoker 权重不等于 WeightedRoundRobin 中保存的权重,说明权重变化了,此时进行更新
            if (weight != weightedRoundRobin.getWeight()) {
                //更新权重
                weightedRoundRobin.setWeight(weight);
            }
            //让 current 加上自身权重,等价于 current += weight
            long cur = weightedRoundRobin.increaseCurrent();
            //设置lastUpdate,代表近期更新过
            weightedRoundRobin.setLastUpdate(now);
            if (cur > maxCurrent) {
                //maxCurrent更新为cur
                maxCurrent = cur;
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            totalWeight += weight;
        }
        //
        if (!updateLock.get() && invokers.size() != map.size()) {
            if (updateLock.compareAndSet(false, true)) {
                try {
                    // copy -> modify -> update reference
                    //拷贝到 newMap中
                    ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
                    newMap.putAll(map);
                    //遍历修改删除过期的记录
                    Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, WeightedRoundRobin> item = it.next();
                        if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
                            it.remove();
                        }
                    }
                    //更新methodWeightMap
                    methodWeightMap.put(key, newMap);
                } finally {
                    updateLock.set(false);
                }
            }
        }
        if (selectedInvoker != null) {
            // 让 current 减去权重总和,等价于 current -= totalWeight
            selectedWRR.sel(totalWeight);
            //返回最大current的Invoker
            return selectedInvoker;
        }
        // should not happen here
        return invokers.get(0);
    }

}

先看懂原理再去理解代码,其实并不困难,上述的代码无非就是每个invoker维护自己的WeightedRoundRobin对象,没有创建该invoker的WeightedRoundRobin对象,如果有的话判断下invoker的权重是否变化了,有变化更新下,计算每个invoker的WeightedRoundRobin中维护的currentWeight变量,找到currentWeight最大的那个即我们最终选择的invoker,找到这个invoker我们还要更新下他的currentWeight,即减去总权重就好了。在中间过程过滤掉长时间未更新的节点因为该节点可能挂了,invokers 中不包含该节点,所以该节点的 lastUpdate 长时间无法被更新。

ConsistentHashLoadBalance

一致性 hash 算法由麻省理工学院的 Karger 及其合作者于1997年提出的,算法提出之初是用于大规模缓存系统的负载均衡。它的工作过程是这样的,首先根据 ip 或者其他的信息为缓存节点生成一个 hash,并将这个 hash 投射到 [0, 232 - 1] 的圆环上。当有查询或写入请求时,则为缓存项的 key 生成一个 hash 值。然后查找第一个大于或等于该 hash 值的缓存节点,并到这个节点中查询或写入缓存项。如果当前节点挂了,则在下一次查询或写入缓存时,为缓存项查找另一个大于其 hash 值的缓存节点即可。大致效果如下图所示,每个缓存节点在圆环上占据一个位置。如果缓存项的 key 的 hash 值小于缓存节点 hash 值,则到该缓存节点中存储或读取缓存项。比如下面绿色点对应的缓存项将会被存储到 cache-2 节点中。由于 cache-3 挂了,原本应该存到该节点中的缓存项最终会存储到 cache-4 节点中。

下面来看看一致性 hash 在 Dubbo 中的应用。我们把上图的缓存节点替换成 Dubbo 的服务提供者,于是得到了下图:

这里颜色相同的节点均属于一个服务提供者,比如invoker1-1,invoker1-2,...,invoker1-160。这样的目的是通过引入虚拟节点,让invoker在圆环上分散开来,避免数据倾斜问题。所谓数据倾斜是指,由于节点不够分散,导致大量请求落到了同一个节点上,而其他节点只会接收到了少量请求的情况。比如:

如上,由于 Invoker-1 和 Invoker-2 在圆环上分布不均,导致系统中75%的请求都会落到 Invoker-1 上,只有 25% 的请求会落到 Invoker-2 上。解决这个问题办法是引入虚拟节点,通过虚拟节点均衡各个节点的请求量。

public class ConsistentHashLoadBalance extends AbstractLoadBalance {

    private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();

    @SuppressWarnings("unchecked")
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //获取调用方法名称
        String methodName = RpcUtils.getMethodName(invocation);
        //group/interface:version.methodName
        String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
        //获取 invokers 原始的 hashcode
        int identityHashCode = System.identityHashCode(invokers);
        //从ConcurrentMap<String, ConsistentHashSelector<?>> selectors 选取一个ConsistentHashSelector
        //就是说group/interface:version.methodName构成一个hash环
        ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
        //如果没有创建ConsistentHashSelector或者invokers列表发生了改变,均需要重新创建
        //ConsistentHashSelector
        if (selector == null || selector.identityHashCode != identityHashCode) {
            // 创建新的 ConsistentHashSelector
            selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
            selector = (ConsistentHashSelector<T>) selectors.get(key);
        }
        //调用 ConsistentHashSelector 的 select 方法选择 Invoker
        return selector.select(invocation);
    }

    private static final class ConsistentHashSelector<T> {...}

}

上述方法首先根据获取服务方法名称组成的key,然后计算invokers的hashcode值,然后根据key从selectors ConcurrentMap<String, ConsistentHashSelector<?>>中获取ConsistentHashSelector,如果selectors中没有或者invokers列表内容发生了变化,都需要重新创建一个ConsistentHashSelector对象。然后调用ConsistentHashSelector对象的select方法获取一个Invoker。

ConsistentHashSelector

/**
         * key- 提供者address的hash算法得到的值,value-Invoker对象
         */
        private final TreeMap<Long, Invoker<T>> virtualInvokers;
        /**
         * 分片数量
         */
        private final int replicaNumber;
        /**
         * invokers列表求得的hashcode
         */
        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]);
            }
            /**
             * 同一个invoker按照分片数量均匀hash到virtualInvokers中
             */
            for (Invoker<T> invoker : invokers) {
                //服务提供者地址
                String address = invoker.getUrl().getAddress();
                //分片数量除以4
                for (int i = 0; i < replicaNumber / 4; i++) {
                    //对 address + i 进行 md5 运算,得到一个长度为16的字节数组
                    byte[] digest = md5(address + i);
                    for (int h = 0; h < 4; h++) {
                        //hash算法根据digest和h的数值分散提供者
                        long m = hash(digest, h);
                        virtualInvokers.put(m, invoker);
                    }
                }
            }
        }

方法的上半部分主要是初始化成员变量virtualInvokers,identityHashCode,replicaNumber,argumentIndex成员变量,下半部分主要是根据dubbo自己的hash算法根据分片数量replicaNumber将invokers列表中的每个invoker均匀的hash到virtualInvokers中。

ConsistentHashSelector.select(Invocation invocation)

public Invoker<T> select(Invocation invocation) {
            String key = toKey(invocation.getArguments());
            // 对参数 key 进行 md5 运算
            byte[] digest = md5(key);
            //取 digest 数组的前四个字节进行 hash 运算,再将 hash 值传给 selectForKey 方法,
            //寻找合适的 Invoker
            return selectForKey(hash(digest, 0));
        }

        /**
         * 对argumentIndex位置处的调用方法的参数拼接成字符串后进行hash
         */
        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) {
            // 到 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();
            }
            return entry.getValue();
        }
  • 1.根据调用传来的参数和初始化时赋值的参数下标数组求得key,然后在根据dubbo自己的hash算法先对key进行md5然后在把digest对应的字节hash获取一个key。
  • 2.根据dubbo的hash算法求得hashcode调用virtualInvokers的trailMap返回大于该hashcode的后半部分Map.Entry,然后取的Map.Entry的第一个元素,如果为null那么直接获取virtualInvokers的第一个元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值