十三:Dubbo负载均衡(四)ShortestResponseLoadBalance

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值