版本权重功能的详细设计-下-功能的执行
本章节将详细介绍如何根据权重值来选择服务
还是直接来到 LinkFlowRoundRobinLoadBalancer#getInstanceResponse 方法
WeightInfoWrapper weightInfoWrapper = linkFlowWeight.parseWeightInfo();
if (linkFlowWeight.isServiceWeight(instances,weightInfoWrapper)) {
ServiceInstance serviceInstance = linkFlowWeight.selectServiceInstance(instances, weightInfoWrapper);
instances.clear();
instances.add(serviceInstance);
}
本章节就是要从 linkFlowWeight.selectServiceInstance(instances, weightInfoWrapper) 这里开始进行分析
版本权重的执行
WeightDefinitionInfo 的作用是将服务实例和对应的权重值关联起来
@Data
@AllArgsConstructor
public class WeightDefinitionInfo {
private ServiceInstance serviceInstance;
private Integer weightValue;
}
public ServiceInstance selectServiceInstance(List<ServiceInstance> servers, WeightInfoWrapper weightInfoWrapper){
//解析权重信息,将服务实例和权重值封装到一个对象中,然后放到集合中
List<WeightDefinitionInfo> weightDefinitionInfoList = servers.stream().map(serviceInstance -> {
//解析权重值
int weightValue = getWeightValue(serviceInstance, weightInfoWrapper);
//将服务实例和权重值进行封装
return new WeightDefinitionInfo(serviceInstance, weightValue);
}).toList();
//创建一个权重随机选择器
WeightedRandomSelector weightedRandomSelector = new WeightedRandomSelector(weightDefinitionInfoList);
//获取随机的服务实例
return weightedRandomSelector.getRandomServer();
}
版本权重的解析
关于解析部分的在上一章节已经做了详细讲解,这里就不再重复了,当获取到具体的权重值后,就会将服务实例和权重值封装到 WeightDefinitionInfo 对象里