深入源码理解Dubbo负载均衡算法原理

上篇相关博客:一文彻底理解Dubbo SPI 自适应(Adaptive)拓展原理

1.Dubbo负载均衡简介

LoadBalance 中文意思为负载均衡,它的职责是将网络请求,或者其他形式的负载“均摊”到不同的机器上。避免集群中部分服务器压力过大,而另一些服务器比较空闲的情况。通过负载均衡,可以让每台服务器获取到适合自己处理能力的负载。在为高负载服务器分流的同时,还可以避免资源浪费,一举两得。负载均衡可分为软件负载均衡和硬件负载均衡。硬件负载均衡器,常见的有NetScaler、F5、Radware和Array等,在我们日常开发中一般很难接触到硬件负载均衡。但软件负载均衡还是可以接触到的,软件负载均衡器,较流行的有LVS,haproxy,nginx。在 Dubbo 中,也有负载均衡的概念和相应的实现。Dubbo 需要对服务消费者的调用请求进行分配,避免少数服务提供者负载过大。服务提供者负载过大,会导致部分请求超时。因此将负载均衡到每个服务提供者上,是非常必要的。Dubbo 提供了4种负载均衡实现,分别是基于权重随机算法的 RandomLoadBalance、基于最少活跃调用数算法的 LeastActiveLoadBalance、基于 hash 一致性的 ConsistentHashLoadBalance,以及基于加权轮询算法的 RoundRobinLoadBalance。本文在编写是基于 Dubbo 2.7.7 的源码。

2.Dubbo负载均衡源码

2.1 LoadBalance接口及抽象实现

在 Dubbo 中,所有负载均衡实现类均继承自 AbstractLoadBalance,该类实现了 LoadBalance 接口,并封装了一些公共的逻辑。所以在分析负载均衡实现之前,先来看一下LoadBalance 接口定义及 AbstractLoadBalance实现逻辑。

LoadBalance 接口定义

/**
 * 
 *负载均衡也是基于Dubbo SPI机制实现的,默认是RandomLoadBalance(基于权重随机算法)
 *
 */
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {

    /**
     * 从所有可用的(比如经过路由过滤等)执行者中选择一个返回
     *
     * @param invokers   所有可行执行者.
     * @param url        refer url
     * @param invocation 程序的调用者
     * @return 负载均衡选出的一个执行者(即被调用服务)
     */
    @Adaptive("loadbalance")
    <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;

}

AbstractLoadBalance对接口select方法的实现逻辑

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        //集合是如果没有可用执行者直接返回空
    	if (CollectionUtils.isEmpty(invokers)) {
            return null;
        }
    	//集合中如果只有一个可用的执行者,直接返回,不需要负载均衡介入
        if (invokers.size() == 1) {
            return invokers.get(0);
        }
        //调用子类实现的具体负载均衡算法进行选择
        return doSelect(invokers, url, invocation);
    }
    
    protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation);

AbstractLoadBalance服务提供者权重计算逻辑

  /**
	 * 该过程主要用于保证当服务运行时长小于服务预热时间时,对服务进行降权,避免让服务在启动之初就处于高负载状态。 服务预热是一个优化手段,与此类似的还有 JVM
	 * 预热。 主要目的是让服务启动后“低功率”运行一段时间,使其效率慢慢提升至最佳状态。
	 * 
	 * @param uptime
	 * @param warmup
	 * @param weight
	 * @return
	 */
	static int calculateWarmupWeight(int uptime, int warmup, int weight) {
		// 根据运行时间和预热时间的比例,计算权重,计算结果介于1-weight之间
		int ww = (int) (uptime / ((float) warmup / weight));
		return ww < 1 ? 1 : (Math.min(ww, weight));
	}
	
	 /**
     * 根据预热时间及正常运行时间计算调用程序的权重
     *
     */
    int getWeight(Invoker<?> invoker, Invocation invocation) {
        int weight;
        //取出调用URL
        URL url = invoker.getUrl();
        // 多注册中心的权重计算方式(如果调用的是注册中心服务则从URL中获取(registry.weight)权重,默认100)
        if (REGISTRY_SERVICE_REFERENCE_PATH.equals(url.getServiceInterface())) {
            weight = url.getParameter(REGISTRY_KEY + "." + WEIGHT_KEY, DEFAULT_WEIGHT);
        } else {
        	//不是调用注册中心服务,则用具体调用服务名从URL中获取权重值(默认也是100)
            weight = url.getMethodParameter(invocation.getMethodName(), WEIGHT_KEY, DEFAULT_WEIGHT);
            if (weight > 0) {
            	//从URL中获取时间戳(timestamp)的值,默认为0
                long timestamp = invoker.getUrl().getParameter(TIMESTAMP_KEY, 0L);
                if (timestamp > 0L) {
                	//计算服务运行时间
                    long uptime = System.currentTimeMillis() - timestamp;
                    if (uptime < 0) {//运行时间小于0则返回权重1
                        return 1;
                    }
                    // 获取服务预热时间,默认为10分钟
                    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 加权随机 RandomLoadBalance

RandomLoadBalance 是加权随机算法的具体实现,它的算法思想很简单。假设我们有一组服务器 servers = [A, B, C],他们对应的权重为 weights = [2, 4, 6],权重总和为12。现在把这些权重值平铺在一维坐标值上,[0, 2) 区间属于服务器 A,[2, 6) 区间属于服务器 B,[6, 12) 区间属于服务器 C。接下来通过随机数生成器生成一个范围在 [0, 12) 之间的随机数,然后计算这个随机数会落到哪个区间上。比如数字3会落到服务器 B 对应的区间上,此时返回服务器 B 即可。权重越大的机器,在坐标轴上对应的区间范围就越大,因此随机数生成器生成的数字就会有更大的概率落到此区间内。只要随机数生成器产生的随机数分布性很好,在经过多次选择后,每个服务器被选中的次数比例接近其权重比例。
当然 RandomLoadBalance 也存在一定的缺点,当调用次数比较少时,Random 产生的随机数可能会比较集中,此时多数请求会落到同一台服务器上。这个缺点并不是很严重,多数情况下可以忽略。RandomLoadBalance 是一个简单,高效的负载均衡实现,因此 Dubbo 选择它作为缺省实现。

/**
 * 加权随机算法RandomLoadBalance实现: 如果权重都相同,那么它将使用random.nextInt(invoker的数量);
 * 如果权重不同,则使用random.nextInt(w1+w2+...+wn)。
 *  注意:如果机器的性能比其他机器好,可以设置更大的重量; 如果性能不太好,可以设置较小的权重。
 */
public class RandomLoadBalance extends AbstractLoadBalance {

	public static final String NAME = "random";

	/**
	 * Select one invoker between a list using a random criteria
	 * 
	 * @param invokers   List of possible invokers
	 * @param url        URL
	 * @param invocation Invocation
	 * @param <T>
	 * @return The selected invoker
	 */
	@Override
	protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
		// Number of invokers
		int length = invokers.size();
		// Every invoker has the same weight?
		boolean sameWeight = true;
		// the weight of every invokers
		int[] weights = new int[length];
		// the first invoker's weight
		int firstWeight = getWeight(invokers.get(0), invocation);
		weights[0] = firstWeight;
		// The sum of weights
		int totalWeight = firstWeight;
		// 循环计算权重的和
		// 循环确认权重和是否一致
		for (int i = 1; i < length; i++) {
			int weight = getWeight(invokers.get(i), invocation);
			// save for later use
			weights[i] = weight;
			// Sum
			totalWeight += weight;
			if (sameWeight && weight != firstWeight) {
				sameWeight = false;
			}
		}
		if (totalWeight > 0 && !sameWeight) {
			// 如果权重和大于0 并且权重Invoker的不完全相同,则随机一个(0-totalWeight)权重和之间的数字
			int offset = ThreadLocalRandom.current().nextInt(totalWeight);
			// 根据随机值,计算该随机值属于哪一个Invoker的区间,并返回改Invoker
			for (int i = 0; i < length; i++) {
				offset -= weights[i];
				if (offset < 0) {
					return invokers.get(i);
				}
			}
		}
		// 如果权重和等于0,或者所有invoker的权重值一样的,则直接随机一个Invoker返回
		return invokers.get(ThreadLocalRandom.current().nextInt(length));
	}

}

2.3 加权最小活跃数 LeastActiveLoadBalance

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

public class LeastActiveLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "leastactive";

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // 服务提供者(Invoker)数量
        int length = invokers.size();
        // 最小活跃数
        int leastActive = -1;
        // 最小活跃数Invoker的数量(多个Invoker的最小活跃数相同)
        int leastCount = 0;
        // 最小活跃数Invoker对应的下标
        int[] leastIndexes = new int[length];
        // 每个Invoker的权重
        int[] weights = new int[length];
        // 所有最不活跃调用程序的预热权重之和
        int totalWeight = 0;
        // 第一个最小活跃Invoker的权重
        int firstWeight = 0;
        // 所有最小活跃Invoker的权重是否一致
        boolean sameWeight = true;


        // 找出所有最小活跃Invoker
        for (int i = 0; i < length; i++) {
            Invoker<T> invoker = invokers.get(i);
            // 获取Invoker的活跃数
            int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
            // 获取Invoker的权重,默认100(该方法在抽象类中实现)
            int afterWarmup = getWeight(invoker, invocation);
            // 保存当前Invoker的权重值
            weights[i] = afterWarmup;
            // 如果当前Invoker是活跃数最小的Invoker(最小活跃数为-1或者比当前Invoker活跃数大)
            if (leastActive == -1 || active < leastActive) {
                //更新最小小活跃数为当前的Invoker活跃数
                leastActive = active;
                // 重置最小活跃Invoker数量为-1
                leastCount = 1;
                // 设置当前Invoker为最小活跃Invoker的第一个值
                leastIndexes[0] = i;
                // 重置总权重为当前Invoker权重
                totalWeight = afterWarmup;
                // 重置第一个最小活跃Invoker的权重为当前Invoker权重
                firstWeight = afterWarmup;
                //设置所有Invoker权重相同
                sameWeight = true;
                //如果当前Invoker活跃数和记录中的最小活跃数相同
            } else if (active == leastActive) {
                //记录大当前Invoker到最小Invoker下标数组
                leastIndexes[leastCount++] = i;
                // 总权重值加上当前的Invoker权重
                totalWeight += afterWarmup;
                // 之前所有最小Invoker的权重相同并当前权重和记录中的最下权重不同,则更新sameWeight为false
                if (sameWeight && i > 0
                        && afterWarmup != firstWeight) {
                    sameWeight = false;
                }
            }
        }
        if (leastCount == 1) {
            // 如果最小活跃的Invoker只有一个,则直接返回
            return invokers.get(leastIndexes[0]);
        }
        if (!sameWeight && totalWeight > 0) {
            // 如果所有最小活跃的权重不都相同并且总权重大于0, 则在[0-totalWeight)范围随机一个数
            int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
            // 根据随机值,找出对应区间的Invoker返回
            for (int i = 0; i < leastCount; i++) {
                int leastIndex = leastIndexes[i];
                offsetWeight -= weights[leastIndex];
                if (offsetWeight < 0) {
                    return invokers.get(leastIndex);
                }
            }
        }
        // 如果所有最小活跃Invoker权重相同或者总权重等于0,则随机返回一个Invoker
        return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
    }
}

2.4 加权轮询 RoundRobinLoadBalance

在详细分析源码前,我们先来了解一下什么是加权轮询。这里从最简单的轮询开始讲起,所谓轮询是指将请求轮流分配给每台服务器。举个例子,我们有三台服务器 A、B、C。我们将第一个请求分配给服务器 A,第二个请求分配给服务器 B,第三个请求分配给服务器 C,第四个请求再次分配给服务器 A。这个过程就叫做轮询。轮询是一种无状态负载均衡算法,实现简单,适用于每台服务器性能相近的场景下。但现实情况下,我们并不能保证每台服务器性能均相近。如果我们将等量的请求分配给性能较差的服务器,这显然是不合理的。因此,这个时候我们需要对轮询过程进行加权,以调控每台服务器的负载。经过加权后,每台服务器能够得到的请求数比例,接近或等于他们的权重比。比如服务器 A、B、C 权重比为 5:2:1。那么在8次请求中,服务器 A 将收到其中的5次请求,服务器 B 会收到其中的2次请求,服务器 C 则收到其中的1次请求。

public class RoundRobinLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "roundrobin";
    
    private static final 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;
        }
        /**
         * 设置服务提供者权重,并初始化当前权重为0
         * @param weight
         */
        public void setWeight(int weight) {
            this.weight = weight;
            current.set(0);
        }
        /**
         * current += weightl;
         * @return
         */
        public long increaseCurrent() {
            return current.addAndGet(weight);
        }
        /**
         * current -= total;
         * @param total
         */
        public void sel(int total) {
            current.addAndGet(-1 * total);
        }
        public long getLastUpdate() {
            return lastUpdate;
        }
        public void setLastUpdate(long lastUpdate) {
            this.lastUpdate = lastUpdate;
        }
    }
    //最外层为服务类名 + 方法名,第二层为 url(标识某个具体服务) 到 WeightedRoundRobin 的映射关系。
    private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
    //更新锁(原子操作)
    private AtomicBoolean updateLock = new AtomicBoolean();
    
    
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    	// 调用服务可key+"."+方法名(如UserService.update)
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        // 从缓冲找中获取某个调用的<url,WeightedRoundRobin>所有映射
        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;
        //遍历所有的提供者列表
        for (Invoker<T> invoker : invokers) {
        	//获取Invoker的URL标识
            String identifyString = invoker.getUrl().toIdentityString();
            //计算权重
            int weight = getWeight(invoker, invocation);
            //从缓存中获取WeightedRoundRobin
            WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
            // 如果没有则新增一个,放入缓存中并赋值weightedRoundRobin
            if (weightedRoundRobin == null) {
            	// 新增WeightedRoundRobin实例并设置权重
                weightedRoundRobin = new WeightedRoundRobin();
                weightedRoundRobin.setWeight(weight);
                // 使用putIfAbsent放入缓存,防止其他线程设置
                map.putIfAbsent(identifyString, weightedRoundRobin);
                weightedRoundRobin = map.get(identifyString);
            }
            //如果权重改变了,则更新WeightedRoundRobin权重值
            if (weight != weightedRoundRobin.getWeight()) {
                weightedRoundRobin.setWeight(weight);
            }
            // 更新current权重(current += weightl)
            long cur = weightedRoundRobin.increaseCurrent();
            // 设置上次更新时间为当前时间
            weightedRoundRobin.setLastUpdate(now);
            //如果当前权重大于最大的当前权重
            if (cur > maxCurrent) {
            	//更新最大去权重
                maxCurrent = cur;
                //设置当前的Invoker为选出的Invoker
                selectedInvoker = invoker;
                //选择的权重WeightedRoundRobin
                selectedWRR = weightedRoundRobin;
            }
            //计算权重和
            totalWeight += weight;
        }
        
        // 如果未加锁并且invokers和缓存中记录的数量不同,则尝试获取锁做更新操作
        if (!updateLock.get() && invokers.size() != map.size()) {
            if (updateLock.compareAndSet(false, true)) {
                try {
                    // 复制一份新的 <url, WeightedRoundRobin>
                    ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<>(map);
                    //对 <url, WeightedRoundRobin> 进行检查,过滤掉长时间未被更新的节点,,默认阈值为60秒。
                    newMap.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
                    methodWeightMap.put(key, newMap);
                } finally {
                    updateLock.set(false);
                }
            }
        }
        // 如果选出了提供者
        if (selectedInvoker != null) {
        	//更新当前权重减去总的权重( current -= total)
            selectedWRR.sel(totalWeight);
            return selectedInvoker;
        }
        // 如果没有选出则直接返回第0个提供者,正常情况是不会执行的
        return invokers.get(0);
    }

}

2.5 一致性Hash ConsistentHashLoadBalance

一致性 hash 算法由麻省理工学院的 Karger 及其合作者于1997年提出的,算法提出之初是用于大规模缓存系统的负载均衡。它的工作过程是这样的,首先根据 ip 或者其他的信息为缓存节点生成一个 hash,并将这个 hash 投射到 [0,4 294 967 295] 的圆环上。当有查询或写入请求时,则为缓存项的 key 生成一个 hash 值。然后查找第一个大于或等于该 hash 值的缓存节点,并到这个节点中查询或写入缓存项。如果当前节点挂了,则在下一次查询或写入缓存时,为缓存项查找另一个大于其 hash 值的缓存节点即可。大致效果如下图所示,每个缓存节点在圆环上占据一个位置。如果缓存项的 key 的 hash 值小于缓存节点 hash 值,则到该缓存节点中存储或读取缓存项。比如下面绿色点对应的缓存项将会被存储到 cache-2 节点中。由于 cache-3 挂了,原本应该存到该节点中的缓存项最终会存储到 cache-4 节点中。在这里插入图片描述
我们把上图的缓存节点替换成 Dubbo 的服务提供者,这里相同颜色的节点均属于同一个服务提供者,比如 Invoker1-1,Invoker1-2,……, Invoker1-160。这样做的目的是通过引入虚拟节点,让 Invoker 在圆环上分散开来,避免数据倾斜问题。所谓数据倾斜是指,由于节点不够分散,导致大量请求落到了同一个节点上,而其他节点只会接收到了少量请求的情况。在这里插入图片描述

public class ConsistentHashLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "consistenthash";

    /**
     * Hash nodes name
     */
    public static final String HASH_NODES = "hash.nodes";

    /**
     * Hash arguments name
     */
    public static final String HASH_ARGUMENTS = "hash.arguments";
    //<调用服务key(如UserService.update),ConsistentHashSelector>
    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) {
    	// 获取调用服务方法名称,并拼接缓存key
        String methodName = RpcUtils.getMethodName(invocation);
        String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
        // 获取调用者列表的hash值
        int invokersHashCode = invokers.hashCode();
        //从缓存中获取ConsistentHashSelector
        ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
        //如果没有缓存中不存在或者hash值发生了变化即服务提供者发生了变化
        if (selector == null || selector.identityHashCode != invokersHashCode) {
        	//新增ConsistentHashSelector实例并存入缓存
            selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, invokersHashCode));
            selector = (ConsistentHashSelector<T>) selectors.get(key);
        }
        //调用ConsistentHashSelector的选择方法返回服务提供者
        return selector.select(invocation);
    }

    private static final class ConsistentHashSelector<T> {
    	//虚拟节点
        private final TreeMap<Long, Invoker<T>> virtualInvokers;
        //虚拟节点数
        private final int replicaNumber;
        // hash 值
        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计算的下标,默认是0
            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]);
            }
            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);
                    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);
                        // 存放虚拟节点调用者
                        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 方法选出提供者
            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) {
        	// 到 TreeMap 中查找第一个节点值大于或等于当前 hash 的 Invoker
            Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
            if (entry == null) {
            	//没有找到则选择头结点
                entry = virtualInvokers.firstEntry();
            }
            //返回该虚拟节点的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;
        }

        private byte[] md5(String value) {
            MessageDigest md5;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            md5.reset();
            byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
            md5.update(bytes);
            return md5.digest();
        }

    }

}

更多源码请参考dubbo源码中的dubbo-cluster模块:https://github.com/qqxhb/dubbo/tree/master/dubbo-cluster

发布了131 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43792385/article/details/105341105