// 注册实例@OverridepublicvoiddoRegister(ServiceInstanceserviceInstance)throwsRuntimeException{if(enableRegister){kubernetesClient.pods().inNamespace(namespace)// 选择当前 pod.withName(currentHostname).edit(pod->newPodBuilder(pod).editOrNewMetadata()// 添加到注解.addToAnnotations(KUBERNETES_PROPERTIES_KEY,JsonUtils.toJson(serviceInstance.getMetadata())).endMetadata().build());if(logger.isInfoEnabled()){logger.info("Write Current Service Instance Metadata to Kubernetes pod. "+"Current pod name: "+currentHostname);}}}
// 方法的逻辑:查询出所有的 pod 和 endpoint,以 endpoint 为准,然后对比,挑选出可用的 pod,最终包装为 serviceInstanceprivateList<ServiceInstance>toServiceInstance(Endpointsendpoints,StringserviceName){Map<String,String>serviceSelector=getServiceSelector(serviceName);if(serviceSelector==null){returnnewLinkedList<>();}// 获取 podMap<String,Pod>pods=kubernetesClient.pods().inNamespace(namespace).withLabels(serviceSelector).list().getItems().stream().collect(Collectors.toMap(pod->pod.getMetadata().getName(),pod->pod));List<ServiceInstance>instances=newLinkedList<>();Set<Integer>instancePorts=newHashSet<>();// 获取 portfor(EndpointSubsetendpointSubset:endpoints.getSubsets()){instancePorts.addAll(endpointSubset.getPorts().stream().map(EndpointPort::getPort).collect(Collectors.toSet()));}for(EndpointSubsetendpointSubset:endpoints.getSubsets()){for(EndpointAddressaddress:endpointSubset.getAddresses()){// 检查 endpoint 和 pod 是否关联,Podpod=pods.get(address.getTargetRef().getName());Stringip=address.getIp();// 如果 pod 为 null,说明这个 pod 删除了if(pod==null){logger.warn(REGISTRY_UNABLE_MATCH_KUBERNETES,"","","Unable to match Kubernetes Endpoint address with Pod. "+"EndpointAddress Hostname: "+address.getTargetRef().getName());continue;}// 遍历所有 port,新建 ServiceInstanceinstancePorts.forEach(port->{ServiceInstanceserviceInstance=newDefaultServiceInstance(serviceName,ip,port,ScopeModelUtil.getApplicationModel(getUrl().getScopeModel()));// 从 pod 上获取之前的元数据信息Stringproperties=pod.getMetadata().getAnnotations().get(KUBERNETES_PROPERTIES_KEY);if(StringUtils.isNotEmpty(properties)){serviceInstance.getMetadata().putAll(JsonUtils.toJavaObject(properties,Map.class));instances.add(serviceInstance);}else{...}});}}returninstances;}