dubbo提供四种负载均衡策略:随机、轮询、最少活动、一致性hash
一、RandomLoadBalance——随机
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——totalweight(不包含)中随机一个数 int offset = ThreadLocalRandom.current().nextInt(totalWeight); // 返回随机数对应数组的invoker for (int i = 0; i < length; i++) { offset -= weights[i]; if (offset < 0) { return invokers.get(i); } } } // 所有节点权重相等或为0,从数组中随机返回一个invoker return invokers.get(ThreadLocalRandom.current().nextInt(length)); }
总结:随机负载均衡:根据每个节点权重,进行随机(使用ThreadLocalRandom保证线程安全),具体分为了两种情况:
1、每个节点权重相同,随机返回一个invoker。
2、权重不相同,根据总权重生成一个随机数,然后根据随机数区间,返回对应的invoker。
特点:少量请求,可能会发生倾斜,当请求变多时,趋向均衡。