/** * @param serviceInstanceListSupplierProvider a provider of * {@link ServiceInstanceListSupplier} that will be used to get available instances * @param serviceId id of the service for which to choose an instance */ // 构造函数,使用给定的 serviceInstanceListSupplierProvider、serviceId 和一个随机的种子位置初始化 RoundRobinLoadBalancer。 publicRoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) { this(serviceInstanceListSupplierProvider, serviceId, newRandom().nextInt(1000)); }
/** * @param serviceInstanceListSupplierProvider a provider of * {@link ServiceInstanceListSupplier} that will be used to get available instances * @param serviceId id of the service for which to choose an instance * @param seedPosition Round Robin element position marker */ // 另一个构造函数,允许指定循环轮询的种子位置 publicRoundRobinLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, int seedPosition) { this.serviceId = serviceId; this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider; this.position = newAtomicInteger(seedPosition); }
@SuppressWarnings("rawtypes") @Override // 负责根据循环轮询算法选择一个服务实例 public Mono<Response<ServiceInstance>> choose(Request request) { ServiceInstanceListSuppliersupplier= serviceInstanceListSupplierProvider .getIfAvailable(NoopServiceInstanceListSupplier::new); return supplier.get(request).next() .map(serviceInstances -> processInstanceResponse(supplier, serviceInstances)); } // 这个方法处理选择服务实例后收到的响应,并在有回调时通知 private Response<ServiceInstance> processInstanceResponse(ServiceInstanceListSupplier supplier, List<ServiceInstance> serviceInstances) { Response<ServiceInstance> serviceInstanceResponse = getInstanceResponse(serviceInstances); if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) { ((SelectedInstanceCallback) supplier).selectedServiceInstance(serviceInstanceResponse.getServer()); } return serviceInstanceResponse; } // 负责根据循环轮询算法从提供的列表中生成包含所选服务实例的响应 private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) { if (instances.isEmpty()) { if (log.isWarnEnabled()) { log.warn("No servers available for service: " + serviceId); } returnnewEmptyResponse(); } // Ignore the sign bit, this allows pos to loop sequentially from 0 to // Integer.MAX_VALUE intpos=this.position.incrementAndGet() & Integer.MAX_VALUE; ServiceInstanceinstance= instances.get(pos % instances.size()); returnnewDefaultResponse(instance); } }