[TOC]
前言
本文将带着以下的问题去学习 Dubbo 的负载均衡机制。
- 负载均衡是什么和有什么用?
- Dubbo提供了哪些负载均衡?
- 负载均衡底层实现--源码解析?
1. 负载均衡概述
引用一段维基百科上的解释
负载平衡(Load balancing)是一种计算机技术,用来在多个计算机(计算机集群)、网络连接、CPU、磁盘驱动器或其他资源中分配负载,以达到最优化资源使用、最大化吞吐率、最小化响应时间、同时避免过载的目的。 使用带有负载平衡的多个服务器组件,取代单一的组件,可以通过冗余提高可靠性。负载平衡服务通常是由专用软件和硬件来完成。 主要作用是将大量作业合理地分摊到多个操作单元上进行执行,用于解决互联网架构中的高并发和高可用的问题。
我们现在或多或少有一点关于负载均衡的印象了,那么先来根据实际的场景来举个栗子:
假设我们系统中关于用户信息相关服务都在 consumer-soa 工程中,为了满足海量的请求以及保证用户服务高可用,我们将 consumer-soa 打包部署在3台机器上,我们简称这三台机器为 USER_A、USER_B、USER_C。订单相关服务的工程 order-soa ,它需要得到关于用户的信息,所以引用了 consumer-soa ,假设在下单或者其它的一些操作时,我们需要调用 consumer-soa 中的 cn.xisole.service.consumer.IUserService#getUserInfoByUserId
这个方法去根据用户id去查找用户的信息。如图所示,它调用任意一台机器上的方法总是能够得到正确的用户信息,虽然实际上我们只需要调用其中一台就行了,最终调用哪台按照的规则就是我们的负载均衡。 负载均衡要干的事情就是按照一定的策略选择多态机器中的一台调用,从而达到资源合理配置的目的。 至于为什么要达到资源合理配置呢,因为我们的机器可能配置不一样,有的机器很老了,有的是新加的配置高的,配置高的处理起来就快,所以有可能我们希望更多的请求都落在配置高的机器上。如果配置都一样,我们更希望将很多的请求分配到各个机器上,这样可以最大化使用这些服务资源。

2. Dubbo 的负载均衡实现
Dubbo 提供了4种负载均衡的实现,分别是:
- Random LoadBalance 基于权重的随机负载均衡机制(默认)
- RoundRobin LoadBalance 基于权重的轮询负载均衡机制
- LeastActive LoadBalance 最少活跃数负载均衡机制
- ConsistentHash LoadBalance 一致性哈希负载均衡机制
我们将仍然使用前面的 order-soa 调用 consumer-soa 查询用户信息的例子来分别学习这几种负载均衡。
2.1 Random LoadBalance 基于权重的随机负载均衡机制
当服务启动之后,我们可以在 Dubbo 的控制台上为服务的提供者增加权重(还有对工程分别打包直接写死在 xml 标签中 werght=100 这种方法,但是不推荐使用),比如我们让 USER_A 的权重为 100,USER_B 的权重为 200,USER_C 的权重为 400。这样当请求过来的时候,最终调用到 USER_A 的概率为 1/7 ,调用到 USER_B 的概率为 2/7,调用到USER_C的概率为 4/7 。以为 USER_C 的权重比较大所以调用的几率也会比较高。这就是基于权重的随机负载均衡机制,它并不能准确的预估一次调用一定会调用到的机器,只是在发生次数足够大的情况下概率满足权重比。如下图
它存在随机不确定的问题,只有调用次数多了这个权重才体现出来。

2.2 RoundRobin LoadBalance 基于权重的轮询负载均衡机制
在解释这个负载均衡机制之前,我们简单了解下轮询的概念,轮询其实就是依次对 USER_A,USER_B,USER_C进行调用然后再回来USER_A,USER_B,USER_C调用,这是轮询。基于权重的意思就是,在轮询的时候,需要判断权重比。假设 USER_A 的权重为 100,USER_B 的权重为 200,USER_C 的权重为 400。还是这个例子,我们第一次轮询依次调用了 USER_A,USER_B,USER_C三台机器,第四次请求的时候,本来应该到 USER_A了,但是发现USER_B的权重比A要大,所以调用USER_B了,然后调用USER_C,在第三轮轮询的时候,就会只调用USER_C了。这样它们的调用次数及权重就满足了。过程如下图:
它存在慢的提供者累积请求的问题,比如:USER_C 机器很慢,但没挂,当请求调到 USER_C 时就卡在那,久而久之,所有请求都卡在调到 USER_C 机器上。

2.3 LeastActive LoadBalance 最少活跃数负载均衡机制
还是 USER_A,USER_B,USER_C,这一次我们没有为它们分配权重了,因为权重这个事不会去考虑机器的实际处理情况,如果当一个服务器收到一个耗时的请求,权重的方式可不会管是否耗时,直接就分配过去了,可能会造成堵塞。LeastActive LoadBalance 根据服务器的最小活跃数来分配请求到底给哪个机器执行,这样慢的服务提供者就会收到相对少的请求。假设 USER_A 正在处理 10个请求,USER_B 正在处理4个请求,USER_C正在处理4个请求,那么如果再来一个请求的话将会在 USER_B和USER_C之间随机选择一个机器处理。
2.4 ConsistentHash LoadBalance 一致性哈希负载均衡机制
前面三种情况有考虑服务的均衡分配,服务的活跃性分配,但是没有考虑我们如果想要某个请求一定只使用某台机器这种情况,比如这台机器有一些额外的东西,如缓存、机器上的文件等。并且我们还得考虑这个机器不可用的情况,如果这台机器挂了,那么基于一些虚拟的节点把请求分摊给其它的提供者,这样不会引起服务抖动。一致性 Hash 的情况下,相同参数的请求总是发到同一提供者。并且默认只对第一个参数 Hash,如果要修改,要配置
<dubbo:parameter key="hash.arguments" value="0,1" />
。
虚拟节点默认用 160 份虚拟节点,如果要修改,配置
<dubbo:parameter key="hash.nodes" value="320" />
一致性Hash负载均衡涉及到两个主要的配置参数为hash.arguments 与hash.nodes。
- hash.arguments : 当进行调用时候根据调用方法的哪几个参数生成key,并根据key来通过一致性hash算法来选择调用结点。例如调用方法invoke(String s1,String s2); 若hash.arguments为1(默认值),则仅取invoke的参数1(s1)来生成hashCode。
- hash.nodes: 为结点的副本数。为什么要有虚拟节点呢?我们还是假设 USER_A,USER_B,USER_C 有3个节点,我们把这3个真实的每个节点映射成 M 个虚拟节点,这样我们就有 3 * M 个虚拟节点了,假设M的值是2(实际这个值要比2大很多的,默认是160的大家考虑下),那么就有
USER_A_1,USER_B_2,USER_A_2,USER_C_1,USER_B_1,USER_C_2
它们在一个环上无序排列。如果 USER_A宕机,那么USER_A_1,USER_A_2这2个虚拟节点就近可能会平摊到 USER_B_2,USER_C_1 这2个节点上,可以让某个机器宕机之后所有请求都到同一个机器上的概率大大降低。
3. Dubbo 负载均衡源码解析
3.1 LoadBalance 及 AbstractLoadBalance
关于负载均衡的继承树如下图所示, LoadBalance 是负载均衡的根接口,里面定义了一个 select
方法,用于选择适当的服务提供者。AbstractLoadBalance 实现了 LoadBalance 接口并提供了一些通用的实现。

LoadBalance 的及 AbstractLoadBalance 的源码及注释解析如下:
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {
/**
* 在invoker的列表中选择一个
*
* @param invokers invokers.
* @param url refer url
* @param invocation invocation.
* @return selected invoker.
*/
@Adaptive("loadbalance")
<T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
}
public abstract class AbstractLoadBalance implements LoadBalance {
/**
* 计算权重
*/
static int calculateWarmupWeight(int uptime, int warmup, int weight) {
int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
return ww < 1 ? 1 : (ww > weight ? weight : ww);
}
@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);
}
/**
* 这个选择逻辑才是各个选择策略真正要关注的
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return
*/
protected abstract <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation);
/**
* 获取 invoker 的权重
*/
protected int getWeight(Invoker<?> invoker, Invocation invocation) {
int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
if (weight > 0) {
long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
if (timestamp > 0L) {
int uptime = (int) (System.currentTimeMillis() - timestamp);
int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
if (uptime > 0 && uptime < warmup) {
weight = calculateWarmupWeight(uptime, warmup, weight);
}
}
}
return weight >= 0 ? weight : 0;
}
}
3.2 RandomLoadBalance 基于权重的随机负载均衡
RandomLoadBalance 比较容易,在经过多次请求后,能够将调用请求按照权重值进行“均匀”分配。当然 RandomLoadBalance 也存在一定的缺点,当调用次数比较少时,Random 产生的随机数可能会比较集中,此时多数请求会落到同一台服务器上。这个缺点并不是很严重,多数情况下可以忽略。RandomLoadBalance 是一个简单,高效的负载均衡实现,因此 Dubbo 选择它作为默认的负载均衡策略。
public class RandomLoadBalance extends AbstractLoadBalance {
public static final String NAME = "random";
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// 执行者的列表,可抽象理解为服务的提供者列表(中间其实还需要网络通信一堆东西,暂时简单理解)
int length = invokers.size();
// 所有的执行者权重都一样的开关打开了
boolean sameWeight = true;
// 每个invoker 都有自己的权重,这里弄个数组出来
int[] weights = new int[length];
// 第一个权重
int firstWeight = getWeight(invokers.get(0), invocation);
weights[0] = firstWeight;
// 所有的权重
int totalWeight = firstWeight;
// 这个循环是为了提取各个invoker 的权重 并且顺便看一下权重是否相同
for (int i = 1; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
weights[i] = weight;
totalWeight += weight;
// 检查权重和上一个权重是否相同,不同的话sameWeight置false,表示权重不是完全一样的设置
if (sameWeight && weight != firstWeight) {
sameWeight = false;
}
}
// 如果权重不相同并且有权重的话
if (totalWeight > 0 && !sameWeight) {
// 在这里取一个随机数
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < length; i++) {
// 让随机值 offset 减去权重值,然后得到 invoker,这样可以比较容易得到 权重大的invoker
offset -= weights[i];
if (offset < 0) {
// 返回 invoker
return invokers.get(i);
}
}
}
// 所有权重都一样,那就随机选择一个就是了
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
}
3.3 RoundRobin LoadBalance
基于权重的轮询负载均衡的主要思想就是轮询,并且建立在有权重的情况下。按照前面所说的理解了轮询的概念再来刷源码会事半功倍。
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;
}
public void setWeight(int weight) {
this.weight = weight;
current.set(0);
}
public long increaseCurrent() {
return current.addAndGet(weight);
}
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();
/**
* 获取 invoker 的地址列表
*/
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) {
// 获取 url 到 WeightedRoundRobin 映射表,如果为空表示没有被调用过,创建一个新的,这也是为啥 USER_A,USER_B,USER_C在第一次轮询没有考虑权重的原因
String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
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;
// 下面这个循环主要做了这样几件事情:
// 1. 遍历 Invoker 列表,检测当前 Invoker 是否有相应的 WeightedRoundRobin,没有则创建
// 2. 检测 Invoker 权重是否发生了变化,若变化了,则更新 WeightedRoundRobin 的 weight 字段
// 3. 让 current 字段加上自身权重,等价于 current += weight
// 4. 设置 lastUpdate 字段,即 lastUpdate = now
// 5. 寻找具有最大 current 的 Invoker,以及 Invoker 对应的 WeightedRoundRobin,暂存起来,留作后用
// 6. 计算权重总和
for (Invoker<T> invoker : invokers) {
String identifyString = invoker.getUrl().toIdentityString();
WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
int weight = getWeight(invoker, invocation);
if (weightedRoundRobin == null) {
weightedRoundRobin = new WeightedRoundRobin();
weightedRoundRobin.setWeight(weight);
map.putIfAbsent(identifyString, weightedRoundRobin);
}
if (weight != weightedRoundRobin.getWeight()) {
weightedRoundRobin.setWeight(weight);
}
long cur = weightedRoundRobin.increaseCurrent();
weightedRoundRobin.setLastUpdate(now);
if (cur > maxCurrent) {
maxCurrent = cur;
selectedInvoker = invoker;
selectedWRR = weightedRoundRobin;
}
totalWeight += weight;
}
// 对 <identifyString, WeightedRoundRobin> 进行检查,过滤掉长时间未被更新的节点。
// 该节点可能挂了,invokers 中不包含该节点,所以该节点的 lastUpdate 长时间无法被更新。
// 若未更新时长超过阈值后,就会被移除掉,默认阈值为60秒。
if (!updateLock.get() && invokers.size() != map.size()) {
if (updateLock.compareAndSet(false, true)) {
try {
// copy -> modify -> update reference
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.put(key, newMap);
} finally {
updateLock.set(false);
}
}
}
if (selectedInvoker != null) {
selectedWRR.sel(totalWeight);
// 返回最大的 invoker
return selectedInvoker;
}
// should not happen here
return invokers.get(0);
}
}
3.4 LeastActive LoadBalance
最小活跃次数主要考虑到了机器实际在处理任务能力相关的情况,之前已经介绍过了,请务必看完之前的举例再刷源码
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 的个数,invoker理解为服务的提供者也即是消费者消费服务时服务的执行者
int length = invokers.size();
// 最小的活跃数
int leastActive = -1;
// 具有相同活跃数的 invoker 的个数
int leastCount = 0;
// 用于记录具有相同“最小活跃数”的 Invoker 在 invokers 列表中的下标
int[] leastIndexes = new int[length];
// 每一个invoker的活跃数
int[] weights = new int[length];
// 总的活跃数
int totalWeight = 0;
// 第一个 invoker 的活跃数
int firstWeight = 0;
// 如果所有活跃数相同就是true
boolean sameWeight = true;
/**
* 循环的作用
* 1. 统计所有的活跃数之和及得到各自invoker的活跃数 totalWeight weights
* 2. 得到是否所有的活跃数都相同 sameWeight
* 3. 统计相同活跃数的记录到 leastIndexes
*/
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
int afterWarmup = getWeight(invoker, invocation);
weights[i] = afterWarmup;
if (leastActive == -1 || active < leastActive) {
leastActive = active;
leastCount = 1;
leastIndexes[0] = i;
totalWeight = afterWarmup;
firstWeight = afterWarmup;
sameWeight = true;
} else if (active == leastActive) {
leastIndexes[leastCount++] = i;
totalWeight += afterWarmup;
if (sameWeight && i > 0
&& afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
// 当只有一个 Invoker 具有最小活跃数,此时直接返回该 Invoker 即可,当然了,就你最闲就给你
if (leastCount == 1) {
return invokers.get(leastIndexes[0]);
}
// 活跃数有不相等的
if (!sameWeight && totalWeight > 0) {
// 随机生成一个 [0, totalWeight) 之间的数字
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
// 循环让随机数减去具有最小活跃数的 Invoker 的活跃数,当 offset 小于等于0时,返回相应的 Invoker
for (int i = 0; i < leastCount; i++) {
int leastIndex = leastIndexes[i];
offsetWeight -= weights[leastIndex];
if (offsetWeight < 0) {
return invokers.get(leastIndex);
}
}
}
// 如果活跃数都相等就随机选择一个好了
return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
}
}
3.5 ConsistentHash LoadBalance
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
public static final String NAME = "consistenthash";
/**
* 这里缓存一些信息
*/
private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
/**
* doSelect 方法主要做了一些前置工作,比如检测 invokers 列表是不是变动过,以及创建 ConsistentHashSelector。
* 这些工作做完后,接下来开始调用 ConsistentHashSelector 的 select 方法执行负载均衡逻辑
*/
@SuppressWarnings("unchecked")
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
// 获取 invokers 原始的 hashcode
int identityHashCode = System.identityHashCode(invokers);
ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
// 如果 invokers 是一个新的 List 对象,意味着服务提供者数量发生了变化,可能新增也可能减少了。
// 此时 selector.identityHashCode != identityHashCode 条件成立
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> {
// // 使用 TreeMap 存储 Invoker 虚拟节点
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
/**
* ConsistentHashSelector 的构造方法执行了一系列的初始化逻辑,
* 比如从配置中获取虚拟节点数以及参与 hash 计算的参数下标,
* 默认情况下只使用第一个参数进行 hash
*/
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();
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) {
String address = invoker.getUrl().getAddress();
for (int i = 0; i < replicaNumber / 4; i++) {
byte[] digest = md5(address + i);
for (int h = 0; h < 4; h++) {
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();
}
// 选择一个 invoker 关键
private Invoker<T> selectForKey(long hash) {
// 到 TreeMap 中查找第一个节点值大于或等于当前 hash 的 Invoker
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
if (entry == null) {
//如果 hash 大于 Invoker 在圆环上最大的位置,此时 entry = null, 需要将 TreeMap 的头节点赋值给 entry
entry = virtualInvokers.firstEntry();
}
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;
}
// 获取一个MD5值
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();
}
}
}
4. 总结
本文比较长,先是简单了解了一些负载均衡的一些概念,
然后知道了 Dubbo 提供了4种负载均衡的实现,分别是:
- Random LoadBalance 基于权重的随机负载均衡机制(默认)
- RoundRobin LoadBalance 基于权重的轮询负载均衡机制
- LeastActive LoadBalance 最少活跃数负载均衡机制
- ConsistentHash LoadBalance 一致性哈希负载均衡机制
之后针对每种负载均衡进行了一次举例,最后阅读了负载均衡的源码,了解了这些之后,负载均衡基本有一个比较清晰的认识了,至于使用官网有几种配置可以参考一下。负载均衡模块是笔者第一次阅读 Dubbo 的源码,仔细阅读了官方文档上的很多东西。中间可能有一些 比如 invoker 的概念没有去专门讲,它在 Dubbo 的体系中很重要的,需要了解服务的调用过程才会对之有一个清晰的认识。这部分源码不是很难,主要是要体会负载均衡几种策略的思想。弱鸡的我还是要加把劲!
网友评论