dubbo负载均衡策略及对应源码分析
在集群负载均衡时,Dubbo 提供了多种均衡策略,缺省为 random
随机调用。我们还可以扩展自己的负责均衡策略,前提是你已经从一个小白变成了大牛,嘻嘻
1、Random LoadBalance
1.1 随机,按权重设置随机概率。
1.2 在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重。
1.3 源码分析
- package com.alibaba.dubbo.rpc.cluster.loadbalance;
- import java.util.List;
- import java.util.Random;
- import com.alibaba.dubbo.common.URL;
- import com.alibaba.dubbo.rpc.Invocation;
- import com.alibaba.dubbo.rpc.Invoker;
- /**
- * random load balance.
- *
- * @author qianlei
- * @author william.liangf
- */
- public class RandomLoadBalance extends AbstractLoadBalance {
- public static final String NAME = "random";
- private final Random random = new Random();
- protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- int length = invokers.size(); // 总个数
- int totalWeight = 0; // 总权重
- boolean sameWeight = true; // 权重是否都一样
- for (int i = 0; i < length; i++) {
- int weight = getWeight(invokers.get(i), invocation);
- totalWeight += weight; // 累计总权重
- if (sameWeight && i > 0
- && weight != getWeight(invokers.get(i - 1), invocation)) {
- sameWeight = false; // 计算所有权重是否一样
- }
- }
- if (totalWeight > 0 && ! sameWeight) {
- // 如果权重不相同且权重大于0则按总权重数随机
- int offset = random.nextInt(totalWeight);
- // 并确定随机值落在哪个片断上
- for (int i = 0; i < length; i++) {
- offset -= getWeight(invokers.get(i), invocation);
- if (offset < 0) {
- return invokers.get(i);
- }
- }
- }
- // 如果权重相同或权重为0则均等随机
- return invokers.get(random.nextInt(length));
- }
- }
说明:从源码可以看出随机负载均衡的策略分为两种情况
a. 如果总权重大于0并且权重不相同,就生成一个1~totalWeight(总权重数)的随机数,然后再把随机数和所有的权重值一一相减得到一个新的随机数,直到随机 数小于0,那么此时访问的服务器就是使得随机数小于0的权重所在的机器
b. 如果权重相同或者总权重数为0,就生成一个1~length(权重的总个数)的随机数,此时所访问的机器就是这个随机数对应的权重所在的机器
2、RoundRobin LoadBalance
2.1 轮循,按公约后的权重设置轮循比率。
2.2 存在慢的提供者累积请求的问题,比如:第二台机器很慢,但没挂,当请求调到第二台时就卡在那,久而久之,所有请求都卡在调到第二台上。
2.3 源码分析
- package com.alibaba.dubbo.rpc.cluster.loadbalance;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentMap;
- import com.alibaba.dubbo.common.URL;
- import com.alibaba.dubbo.common.utils.AtomicPositiveInteger;
- import com.alibaba.dubbo.rpc.Invocation;
- import com.alibaba.dubbo.rpc.Invoker;
- /**
- * Round robin load balance.
- *
- * @author qian.lei
- * @author william.liangf
- */
- public class RoundRobinLoadBalance extends AbstractLoadBalance {
- public static final String NAME = "roundrobin";
- private final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
- private final ConcurrentMap<String, AtomicPositiveInteger> weightSequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
- protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
- int length = invokers.size(); // 总个数
- int maxWeight = 0; // 最大权重
- int minWeight = Integer.MAX_VALUE; // 最小权重
- for (int i = 0; i < length; i++) {
- int weight = getWeight(invokers.get(i), invocation);
- maxWeight = Math.max(maxWeight, weight); // 累计最大权重
- minWeight = Math.min(minWeight, weight); // 累计最小权重
- }
- if (maxWeight > 0 && minWeight < maxWeight) { // 权重不一样
- AtomicPositiveInteger weightSequence = weightSequences.get(key);
- if (weightSequence == null) {
- weightSequences.putIfAbsent(key, new AtomicPositiveInteger());
- weightSequence = weightSequences.get(key);
- }
- int currentWeight = weightSequence.getAndIncrement() % maxWeight;
- List<Invoker<T>> weightInvokers = new ArrayList<Invoker<T>>();
- for (Invoker<T> invoker : invokers) { // 筛选权重大于当前权重基数的Invoker
- if (getWeight(invoker, invocation) > currentWeight) {
- weightInvokers.add(invoker);
- }
- }
- int weightLength = weightInvokers.size();
- if (weightLength == 1) {
- return weightInvokers.get(0);
- } else if (weightLength > 1) {
- invokers = weightInvokers;
- length = invokers.size();
- }
- }
- AtomicPositiveInteger sequence = sequences.get(key);
- if (sequence == null) {
- sequences.putIfAbsent(key, new AtomicPositiveInteger());
- sequence = sequences.get(key);
- }
- // 取模轮循
- return invokers.get(sequence.getAndIncrement() % length);
- }
- }
说明:从源码可以看出轮循负载均衡的算法是:
a. 如果权重不一样时,获取一个当前的权重基数,然后从权重集合中筛选权重大于当前权重基数的集合,如果筛选出的集合的长度为1,此时所访问的机器就是集合里面的权重对应的机器
b. 如果权重一样时就取模轮循
3、LeastActive LoadBalance
3.1 最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差(调用前的时刻减去响应后的时刻的值)。
3.2 使慢的提供者收到更少请求,因为越慢的提供者的调用前后计数差会越大
3.3 对应的源码
- package com.alibaba.dubbo.rpc.cluster.loadbalance;
- import java.util.List;
- import java.util.Random;
- import com.alibaba.dubbo.common.Constants;
- import com.alibaba.dubbo.common.URL;
- import com.alibaba.dubbo.rpc.Invocation;
- import com.alibaba.dubbo.rpc.Invoker;
- import com.alibaba.dubbo.rpc.RpcStatus;
- /**
- * LeastActiveLoadBalance
- *
- * @author william.liangf
- */
- public class LeastActiveLoadBalance extends AbstractLoadBalance {
- public static final String NAME = "leastactive";
- private final Random random = new Random();
- protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
- int length = invokers.size(); // 总个数
- int leastActive = -1; // 最小的活跃数
- int leastCount = 0; // 相同最小活跃数的个数
- 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);
- 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) { // 发现更小的活跃数,重新开始
- leastActive = active; // 记录最小活跃数
- leastCount = 1; // 重新统计相同最小活跃数的个数
- leastIndexs[0] = i; // 重新记录最小活跃数下标
- totalWeight = weight; // 重新累计总权重
- firstWeight = weight; // 记录第一个权重
- sameWeight = true; // 还原权重相同标识
- } else if (active == leastActive) { // 累计相同最小的活跃数
- leastIndexs[leastCount ++] = i; // 累计相同最小活跃数下标
- totalWeight += weight; // 累计总权重
- // 判断所有权重是否一样
- if (sameWeight && i > 0
- && weight != firstWeight) {
- sameWeight = false;
- }
- }
- }
- // assert(leastCount > 0)
- if (leastCount == 1) {
- // 如果只有一个最小则直接返回
- return invokers.get(leastIndexs[0]);
- }
- if (! sameWeight && totalWeight > 0) {
- // 如果权重不相同且权重大于0则按总权重数随机
- int offsetWeight = random.nextInt(totalWeight);
- // 并确定随机值落在哪个片断上
- 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则均等随机
- return invokers.get(leastIndexs[random.nextInt(leastCount)]);
- }
- }
说明:源码里面的注释已经很清晰了,大致的意思就是活跃数越小的的机器分配到的请求越多
4、ConsistentHash LoadBalance
4.1 一致性 Hash,相同参数的请求总是发到同一提供者。
4.2 当某一台提供者挂时,原本发往该提供者的请求,基于虚拟节点,平摊到其它提供者,不会引起剧烈变动。
4.3 缺省只对第一个参数 Hash,如果要修改,请配置 <dubbo:parameter key="hash.arguments" value="0,1" />
4.4 缺省用 160 份虚拟节点,如果要修改,请配置 <dubbo:parameter key="hash.nodes" value="320" />
4.5 源码分析
- /*
- * Copyright 1999-2012 Alibaba Group.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package com.alibaba.dubbo.rpc.cluster.loadbalance;
- import java.io.UnsupportedEncodingException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.List;
- import java.util.SortedMap;
- import java.util.TreeMap;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentMap;
- import com.alibaba.dubbo.common.Constants;
- import com.alibaba.dubbo.common.URL;
- import com.alibaba.dubbo.rpc.Invocation;
- import com.alibaba.dubbo.rpc.Invoker;
- /**
- * ConsistentHashLoadBalance
- *
- * @author william.liangf
- */
- 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 key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
- int identityHashCode = System.identityHashCode(invokers);
- ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
- if (selector == null || selector.getIdentityHashCode() != identityHashCode) {
- selectors.put(key, new ConsistentHashSelector<T>(invokers, invocation.getMethodName(), identityHashCode));
- selector = (ConsistentHashSelector<T>) selectors.get(key);
- }
- return selector.select(invocation);
- }
- 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;
- public ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
- this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
- this.identityHashCode = System.identityHashCode(invokers);
- URL url = invokers.get(0).getUrl();
- this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
- 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) {
- for (int i = 0; i < replicaNumber / 4; i++) {
- byte[] digest = md5(invoker.getUrl().toFullString() + i);
- for (int h = 0; h < 4; h++) {
- long m = hash(digest, h);
- virtualInvokers.put(m, invoker);
- }
- }
- }
- }
- public int getIdentityHashCode() {
- return identityHashCode;
- }
- public Invoker<T> select(Invocation invocation) {
- String key = toKey(invocation.getArguments());
- byte[] digest = md5(key);
- Invoker<T> invoker = sekectForKey(hash(digest, 0));
- return invoker;
- }
- 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> sekectForKey(long hash) {
- Invoker<T> invoker;
- Long key = hash;
- if (!virtualInvokers.containsKey(key)) {
- SortedMap<Long, Invoker<T>> tailMap = virtualInvokers.tailMap(key);
- if (tailMap.isEmpty()) {
- key = virtualInvokers.firstKey();
- } else {
- key = tailMap.firstKey();
- }
- }
- invoker = virtualInvokers.get(key);
- return invoker;
- }
- 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[0 + 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 = null;
- try {
- bytes = value.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- md5.update(bytes);
- return md5.digest();
- }
- }
- }
说明:根据传递的参数进行hash然后调用服务,如果两次传递的参数一样就调用的是同一个机器上的服务
5、dubbo官方的文档的负载均衡配置示例
服务端服务级别
<dubbo:service interface="..." loadbalance="roundrobin" />
客户端服务级别
<dubbo:reference interface="..." loadbalance="roundrobin" />
服务端方法级别
<dubbo:service interface="...">
<dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:service>
客户端方法级别
<dubbo:reference interface="...">
<dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:reference>
dubbo负载均衡策略及对应源码分析的更多相关文章
- dubbo负载均衡策略和集群容错策略都有哪些
dubbo负载均衡策略 random loadbalance 默认情况下,dubbo是random load balance随机调用实现负载均衡,可以对provider不同实例设置不同的权重,会按照权 ...
- 3.dubbo 负载均衡策略和集群容错策略都有哪些?动态代理策略呢?
作者:中华石杉 面试题 dubbo 负载均衡策略和集群容错策略都有哪些?动态代理策略呢? 面试官心理分析 继续深问吧,这些都是用 dubbo 必须知道的一些东西,你得知道基本原理,知道序列化是什么协议 ...
- 分布式的几件小事(四)dubbo负载均衡策略和集群容错策略
1.dubbo负载均衡策略 ①random loadbalance 策略 默认情况下,dubbo是random loadbalance 随机调用实现负载均衡,可以对provider不同实例设置不同的权 ...
- 面试系列24 dubbo负载均衡策略和集群容错策略
(1)dubbo负载均衡策略 1)random loadbalance 默认情况下,dubbo是random load balance随机调用实现负载均衡,可以对provider不同实例设置不同的权重 ...
- 面试系列16 dubbo负载均衡策略和集群容错策略都有哪些?动态代理策略呢
(1)dubbo负载均衡策略 1)random loadbalance 默认情况下,dubbo是random load balance随机调用实现负载均衡,可以对provider不同实例设置不同的权重 ...
- dubbo负载均衡策略和集群容错策略都有哪些?动态代理策略呢?
(1)dubbo负载均衡策略 1)random loadbalance 默认情况下,dubbo是random load balance随机调用实现负载均衡,可以对provider不同实例设置不同的权重 ...
- dubbo负载均衡策略和集群容错策略
dubbo负载均衡策略 random loadbalance 默认情况下,dubbo是random load balance随机调用实现负载均衡,可以对provider不同实例设置不同的权重,会按照权 ...
- Dubbo入门到精通学习笔记(十一):Dubbo服务启动依赖检查、Dubbo负载均衡策略、Dubbo线程模型(结合Linux线程数限制配置的实战分享)
文章目录 Dubbo服务启动依赖检查 Dubbo负载均衡策略 Dubbo线程模型(结合Linux线程数限制配置的实战分享) 实战经验分享( ** 属用性能调优**): Dubbo服务启动依赖检查 Du ...
- Dubbo负载均衡策略
在集群负载均衡时,Dubbo提供了多种均衡策略,缺省为random随机调用. 可以自行扩展负载均衡策略,参见:负载均衡扩展Random LoadBalance 随机,按权重设置随机概率. 在一个截面上 ...
随机推荐
- Android项目实战(三十四):蓝牙4.0 BLE 多设备连接
最近项目有个需求,手机设备连接多个蓝牙4.0 设备 并获取这些设备的数据. 查询了很多资料终于实现,现进行总结. ------------------------------------------- ...
- AVAssetWriter 硬编码bug解决
一.需求 直播助手在录屏过程中,产品要求跟随用户手机屏幕旋转,录屏的视频跟随旋转 二.实施方案 目前触手录,iTools PC端均已经实现该功能,并且该功能只适配iOS9和iOS10系统.猜测实现方案 ...
- java面向对象(三)之抽象类,接口,向上转型
java类 java类分为普通类和抽象类,接口,上一节我大概讲了java类的一般格式,今天将抽象类和接口.同时讲一下它们是怎样存储的. 最重要的是理解为什么要有抽象和接口,这样学下来你猜不会迷茫,才能 ...
- ios 初体验<UIButton 控件>
1.创建UIButton 跟其他方式不同,不是直接alloc,init 创建 用工厂化方式创建 UIButton *sureBtn = [UIButton buttonWithType:UIButto ...
- 求N个元素的子集合个数
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt406 一个集合有n个元素,请问怎么算出来它的子集(包括空集和本身)是 2的n ...
- NHibernate教程(5)--CRUD操作
NHibernate之旅(5):探索Insert, Update, Delete操作 2008-10-17 16:31 by 李永京, 42903 阅读, 73 评论, 收藏, 编辑 本节内容 操作 ...
- 【1414软工助教】团队作业2——需求分析&原型设计 得分榜
题目 团队作业2--需求分析&原型设计 作业提交情况情况 本次作业所有团队都按时提交作业. 往期成绩 个人作业1:四则运算控制台 结对项目1:GUI 个人作业2:案例分析 结对项目2:单元测试 ...
- 结对编程1----基于java的四则运算生成器
小组成员:王震(201421123054).王杰(201421123055) Coding地址:https://git.coding.net/a506504661/sssss.git 一.题目描述 我 ...
- sudoku--SE第二次作业
git传送门 编译环境: windows10.vs2017 所用语言: c++ 首先作为一个晚上闭眼的玩家,我先来讲一下我的心路历程: 最开始接到作业的时候心里是拒绝的,刚出了一趟小远门就这样,就很难 ...
- 201521123007《Java程序设计》第4周学习总结
1. 本周学习总结 1.1 尝试使用思维导图总结有关继承的知识点. 1.2 使用常规方法总结其他上课内容. 1.1有关继承的知识点: 1.2有关多态 多态性:相同的形态,不同的行为.体现在相同的方法名 ...