原理源码
原理同最小活跃数负载,算法框架完全相同
计算最小响应时间[总成功请求时间/总成功请求个数 * 当前活跃数]当前活跃数通过filter机制实现,同LeastActiveLoadBalance当前请求时间和个数通过ActiveLimitFilter过滤机制实现
源码获取最短响应时间Invoker集合只有一个返回,存在多个根据权重获取
protectedInvoker doSelect(List > invokers, URL url, Invocation invocation) { ...... 删除其他代码 基本同最小活跃数算法 for (int i = 0; i < length; i++) { Invoker 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)]); }



