SpringCloudGateway路由策略:Nacos同集群优先

使用版本

2.7.3
2021.0.4
2021.0.4.0
注:2021.x版与2.2.x版实现方式有差异,本文档使用2021.x版。附录含相关版本说明

步骤:

1.修改网关、业务模块等配置文件,指定nacos服务集群名

spring:
  cloud:
    nacos:
      discovery:
        cluster-name: MyClusterName

2.gateway模块指定LoadBalancer实现NacosLoadBalancerClientConfiguration

@LoadBalancerClients(defaultConfiguration = NacosLoadBalancerClientConfiguration.class)
public class LoadBalancerConfig {
}

同集群优先实现方式参见源码:

类:com.alibaba.cloud.nacos.loadbalancer.NacosLoadBalancer

private Response getInstanceResponse(
			List serviceInstances) {
		if (serviceInstances.isEmpty()) {
			log.warn("No servers available for service: " + this.serviceId);
			return new EmptyResponse();
		}

		try {
			String clusterName = this.nacosDiscoveryProperties.getClusterName();

			List instancesToChoose = serviceInstances;
			if (StringUtils.isNotBlank(clusterName)) {
				List sameClusterInstances = serviceInstances.stream()
						.filter(serviceInstance -> {
							String cluster = serviceInstance.getMetadata()
									.get("nacos.cluster");
							return StringUtils.equals(cluster, clusterName);
						}).collect(Collectors.toList());
				if (!CollectionUtils.isEmpty(sameClusterInstances)) {
					instancesToChoose = sameClusterInstances;
				}
			}
			else {
				log.warn(
						"A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}",
						serviceId, clusterName, serviceInstances);
			}

			ServiceInstance instance = NacosBalancer
					.getHostByRandomWeight3(instancesToChoose);

			return new DefaultResponse(instance);
		}
		catch (Exception e) {
			log.warn("NacosLoadBalancer error", e);
			return null;
		}

	}

附录:

资料链接

SpringCloudGateway路由策略:Nacos同集群优先_第1张图片

 SpringCloudGateway路由策略:Nacos同集群优先_第2张图片

SpringCloudGateway路由策略:Nacos同集群优先_第3张图片 

 

你可能感兴趣的:(java,springcloud,微服务,服务发现)