用过dubbo的都知道,dubbo服务发布&订阅有2个重要的参数:
version和group
。即消费者和生产者不但需要要接口名完全一致,还需要version和group也完全一致,才能成功的匹配到服务:
version主要作用是某个接口的实现出现不兼容升级的时候,用来过渡,例如老版本申明为version="1.0.0",新版本就可以申明为version="2.0.0";
group主要作用就是某个接口有多个实现类,那么通过group区分,消费者通过group参数决定调用哪个group的服务;
此外这里还有一个作用,如下图所示,为了让本地消费者只调用本地生产者提供的服务,也可以通过version或者group隔离(dubbo的直连也可以实现):
dubbo
那么,在springcloud微服务架构下开发,同样会遇到这个问题,又该怎么解决呢?如下图所示,假设生产者2暴露的xxx-user服务是我们本地开发环境的服务,如何让消费者只调用生产者2提供的服务,而不是在生产者1和生产者2之中选择:
springcloud
源码之中毫无秘密,我们先看服务发现的源码,以consul作为注册中心为例,源码在ConsulServerList.java中:
private List getServers() { if (this.client == null) { return Collections.emptyList(); } String tag = getTag(); // null is ok Response> response = this.client.getHealthServices( this.serviceId, tag, this.properties.isQueryPassing(), createQueryParamsForClientRequest(), this.properties.getAclToken()); if (response.getValue() == null || response.getValue().isEmpty()) { return Collections.emptyList(); } return transformResponse(response.getValue());}
由这段源码可知,从注册中心获取服务时,除了最核心的服务ID(serviceId),还有其他一些参数,例如tag。参数tag就是本文要介绍的实现服务注册&发现隔离性,tag获取源码如下:
public String getQueryTagForService(String serviceId){ String tag = serverListQueryTags.get(serviceId); return tag != null ? tag : defaultQueryTag;}
并且它优先取ConsulDiscoveryProperties中的serverListQueryTags,如果这个集合为空,再尝试取defaultQueryTag:
@ConfigurationProperties("spring.cloud.consul.discovery")@Datapublic class ConsulDiscoveryProperties { /** * Map of serviceId's -> tag to query for in server list. * This allows filtering services by a single tag. */ private Map serverListQueryTags = new HashMap<>(); /** Tag to query for in service list if one is not listed in serverListQueryTags. */ private String defaultQueryTag; ......}
OK,到这里我们就知道服务的消费者可以通过如下两个配置去发现特定tag的服务:
spring.cloud.consul.discovery.serverListQueryTags.xxx-user
=afei,这个参数是指定某个特定服务(例如xxx-user)的某个tag(例如afei)服务提供者。
spring.cloud.consul.discovery.defaultQueryTag
=afei,这个参数是指定所有服务的某个tag(例如afei)服务提供者。
服务生产者只需要指定如下参数即可,且通过ConsulDiscoveryProperties中的tags定义可知,还可以指定多个tag,中间以逗号隔开即可(springboot的实现机制):
spring.cloud.consul.discovery.tags=afei
spring.cloud.consul.discovery.tags=afei,hulk
@ConfigurationProperties("spring.cloud.consul.discovery")@Datapublic class ConsulDiscoveryProperties { /** Tags to use when registering service */ private List tags = new ArrayList<>(); ......}
最后,图解如下,虽然生产者1和生产者2的服务ID都是xxx-user,但是生产者2指定了tag为"afei",那么同样指定了tag为afei消费者只会发现生产者2暴露的服务,而不会找到生产者1暴露的服务:
springcloudtag原理图
事实上springcloud的ConsulDiscoveryProperties.java中还定义了另外两个属性
instanceZone
instanceGroup
,对应的springboot配置如下,也可以解决这个问题
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.