dubbo源码分析第二十五篇一dubbo负载均衡一ShortestResponseLoadBalance加权最短响应时间

文章目录

原理

同最小活跃数负载,算法框架完全相同

  • 计算最小响应时间[总成功请求时间/总成功请求个数 * 当前活跃数]
  • 当前活跃数通过filter机制实现,同LeastActiveLoadBalance
  • 当前请求时间和个数通过ActiveLimitFilter过滤机制实现

在这里插入图片描述

源码

  • 获取最短响应时间Invoker集合
  • 只有一个返回,存在多个根据权重获取

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)]);
}

版权声明:本文为qq_35529969原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。