注意:我们分析的sofa-rpc版本是5.4.0。
图1 RoundRobinLoadBalancer的类继承图
一般的RoundRobin就是轮询服务提供者。例子:假设服务提供者有S1、S2、S3,那么第一次选择S1,第二次则选择S2,第三次则选择S3,第四次则选择S1...这样不断轮询服务提供者。
下面分析sofa-rpc的RoundRobinLoadBalancer实现,sofa-rpc中与上述例子中的实现有点不同。
RoundRobinLoadBalancer的方法doSelect(SofaRequest, List<ProviderInfo>)是该算法的核心,下面我们重点来分析该方法的实现。doSelect方法中的源码如下,建议读者自己从github上down源码下来自己看源码。
@Override
public ProviderInfo doSelect(SofaRequest request, List<ProviderInfo> providerInfos) {
String key = getServiceKey(request); // 每个方法级自己轮询,互不影响
int length = providerInfos.size(); // 服务提供者总个数
PositiveAtomicCounter sequence = sequences.get(key);
if (sequence == null) {
sequences.putIfAbsent(key, new PositiveAtomicCounter());
sequence = sequences.get(key);
}
return providerInfos.get(sequence.getAndIncrement() % length);
}
private String getServiceKey(SofaRequest request) {
StringBuilder builder = new StringBuilder();
builder.append(request.getTargetAppName()).append("#")
.append(request.getMethodName());
return builder.toString();
}
sequences个是concurrentHashMap,如下
ConcurrentMap<String, PositiveAtomicCounter> sequences = new ConcurrentHashMap<String, PositiveAtomicCounter>();
有没有发现sofa-rpc中的实现与我们在开始给出的例子有点不一样。sofa-rpc中的轮询算法比开头例子在维度上更细,sofa-rpc是站在方法method维度上进行的轮询。
1.sofa-rpc为什么站在方法维度实现RoundRobin?如果你能自己提出这个问题,那么说明你已经看懂了sofa-rpc的RoundRobin算法大致实现。谈谈我自己的理解:一个服务提供者,提供很多可供调用的方法,某些方法被调用的频率和次数是高于其它方法的。如果我们站在方法的维度上实现轮询,则这种轮询是更加公平的。可以看出,sofa-rpc的作者还是经过认真思考过的。
2.上述的所有实现,都没有考虑服务提供者带权重的情况,如果要实现WeightRoundRobin算法(考虑权重的轮询算法)呢,如何实现?sofa-rpc中实现了,只是性能有点差,框架作者不推荐使用。
(adsbygoogle = window.adsbygoogle || []).push({});