//org.apache.dubbo.rpc.cluster.loadbalance.ShortestResponseLoadBalance#doSelect
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
...... 删除其他代码 基本同最小活跃数算法
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
每个请求成功时响应的平均时间 [每个请求开始有个时间戳 结束时的时间减去开始时间加入rpcStatus]
long succeededAverageElapsed = rpcStatus.getSucceededAverageElapsed();
获取当前在活跃调用的请求数量
int active = rpcStatus.getActive();
平均请求时间*活跃数表示最小响应时间
long estimateResponse = succeededAverageElapsed * active;
int afterWarmup = getWeight(invoker, invocation);
weights[i] = afterWarmup;
计算处理
if (estimateResponse < shortestResponse) {
shortestResponse = estimateResponse;
shortestCount = 1;
shortestIndexes[0] = i;
totalWeight = afterWarmup;
firstWeight = afterWarmup;
sameWeight = true;
} else if (estimateResponse == shortestResponse) {
shortestIndexes[shortestCount++] = i;
totalWeight += afterWarmup;
if (sameWeight && i > 0
&& afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
最短响应时间相同的Invoker只有一个
if (shortestCount == 1) {
return invokers.get(shortestIndexes[0]);
}
最短响应时间相同的Invoker有多个,且存在权重不同 加权获取
if (!sameWeight && totalWeight > 0) {
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < shortestCount; i++) {
int shortestIndex = shortestIndexes[i];
offsetWeight -= weights[shortestIndex];
if (offsetWeight < 0) {
return invokers.get(shortestIndex);
}
}
}
最短响应时间相同的Invoker有多个,且权重相同 随机获取
return invokers.get(shortestIndexes[ThreadLocalRandom.current().nextInt(shortestCount)]);
}
十三:Dubbo负载均衡(四)ShortestResponseLoadBalance
最新推荐文章于 2024-04-08 11:54:59 发布