SpringCloud全系列(二):Spring Cloud Consul原理解析

目录

1. 背景

2. Consul是什么

3. 为什么选Consul

4. Consul的部署架构

5. Consul的读一致性模式

6. Consul的服务注册和健康检查

7. Quick Start

7.1 Consul的Java客户端

7.2 KV存储Quick Start

7.3 服务注册发现Quick Start

8. Spring Cloud Commons 中的服务注册和发现

8.1 服务发现DiscoveryClient

8.2 服务注册ServiceRegistry

9. Spring Cloud Consul 实现原理

9.1 SCC的自动注入

9.2 SCC应用配置原理

9.3 SCC服务注册原理

9.4 SCC服务发现原理

10. 总结


1. 背景

       我们知道Spring Boot是为了解决Spring使用成本高的问题,Spring Cloud是为了解决分布式系统开发成本高的问题,而在分布式系统中,服务治理又是绕不开的话题,注册中心又是核心中心的核心。而Consul就是为了在云原生上构建注册中心而准备的,尽管这样定义Consul不够全面(Consul还有很多其他能力),但Consul提供的服务发现和注册的能力才是本文的重点。如你所知,Consul不是由Spring Cloud创建出来的新东西,而是出自HashiCorp公司之手,也是其明星产品之一,HashiCorp是一家位于美国加利福尼亚州旧金山的软件公司,专为企业提供云基础设施建设的解决方案,两位创始人都是技术出身(可以简单理解成程序员创业),而且HashiCorp在2021年12月已经上市。

这里给大家看看两位创始人创业初期的照片:  

2. Consul是什么

       没错,在讲Spring Cloud Consul(本文简称SCC)之前,我们要好好聊聊Consul(https://github.com/hashicorp/consul),Consul 采用 Golang 开发,是一个分布式、高可用性和支持多数据中心解决方案,用于分布式的基础架构连接和配置管理系统。可以看出Consul将自己定位成一个底层的基础设施(这个HashiCorp公司对自身的定位相符),支持两种核心能力:连接(注册中心)和配置(KV)。对了,Consul还支持服务网格(What is a service mesh? | Consul by HashiCorp),具有网络分段的能力,就是说你可以在同一个网段通过配置来隔离出多个集群来(逻辑上隔离),这很适合需要灵活构建多套环境的场景。

3. 为什么选Consul

     其实这一直是一个比较难回答的问题,在我所知道的开源软件中,能很容易回答“为什么要有XXX以及为什么选XXX?”这个问题就只有为数不多的几款产品(例如Spring、Netty、Nignx),因为这些开源软件都因为实用性、性能和扩展性暂时所向披靡。那回过头来,我们为什么选择Consul?其实Consul的官网给了一个比较全面的回答:Consul vs. Other Software | Consul by HashiCorp从注册中心视角来说,Consul是一个基于云原生(可以K8S打通)、CP(CAP)、支持多数据中心的注册中心服务,按照创始人的话说:“Consul提供了很多能力,这些能力在业界上都有对应的相似实现,但具备所有这些能力的只有Consul,而且Consul的每种能力都能单独使用,Consul依赖的所有能力都是自己闭环的(换句话说就是Consul依赖的所有能力都是HashiCorp自家开源的产品)”。额外需要强调一点的是Consul支持DNS协议,这在使用DNS来发现服务的场景特别有用,因为服务调用方甚至不需要感知Consul的存在,这在支持一些老的系统很有效。

       我们为啥要放弃ZooKeeper选择Consul?这其实很简单,ZooKeeper不是为注册中心而生,我们知道ZooKeeper是一个分布式协作框架,里面有临时节点和Watch机制,这常常被用来实现服务注册和发现的能力,但这毕竟是“曲线救国”,一些注册中心需要得能力ZooKeeper都没有现成的(比如各式各样的健康检查、合格的服务管理控制台等),而且ZooKeeper也不支持多数据中心。

       Consul和Nacos该如何选?这我给不了太多的建议,毕竟我不认为Consul和Nacos比起来有太多的优势,假如你用Spring Cloud,那么选择Consul会更合适,而如果你用Spring Cloud Alibaba,但当然首选Nacos。还有的人会通过注册中心到底应该是AP还是CP来选择,根据我的经验来看,不管是AP或CP,只要出故障后短时间内能恢复,那么对线上服务都不会有太大的影响(注册中心大多数都有客户端缓存)。

        然而从Spring Cloud的视角来说,它急于找出Eureka的替代品,Consul正好是合适的选择之一。

4. Consul的部署架构

      如果你是一个解决分布式系统问题的系统,那你本身就得是分布式的,我们从Consul的官方架构图开始(为了让有些强迫症的人看起来更舒服,这里给出这张图片的来源地址:Consul Architecture | Consul by HashiCorp):

这张图之所以看起来很复杂,是因为它画了两个数据中心,我们先看这张图的上半部分(即DATACENTER1),可以看出,在Consul集群中有两个角色,一个是Client,另一个是Server,但比较特殊的是,Client是需要单独部署的,一般和服务进程部署在一起,可以理解成服务网格中边车(Sidecar)的作用。我们通过图中两两之间的交互来理解该架构图:

Client->Server:Client(即Client Agent)和Server之间使用的是gRPC通信,有意思的是在Client配置中不需要配置Server的地址,而是配置一个网段,Server也是一样,他们之间可以通过LAN的UDP协议来发现同网段的彼此。

Client->Client:你肯定会感到奇怪,Client和Client也需要交互?没错,在Consul的架构设计中,所有角色都围绕着通过 Gossip 来达成共识,Gossip协议的另一个叫法是传染病或流行病协议,通过广播来通知周边节点,周边节点收到后也进行类似的广播,所以Gossip实现简单,并且有很高的可靠性,但也有缺点,例如容易产生事件风暴,而且达成一致的时间不确定等,抛开这些不说,这意味着Client和Client之间是可以传播和共享“知识”或“认知”的(比如关于活跃Server节点的信息),所以Consul号称任何节点挂了,都不影响Consul的使用。Consul 是通过底层的 Serf 来使用Gossip协议的(注意,Serf也是HashiCorp公司的产品),有关Serf的内容参见https://github.com/hashicorp/serf,本文不做过多介绍。采用Gossip还有一大好处,意味着我们可以动态的往集群中新增或删除节点,而不需用改集群的配置,他们会自动达成共识(发现或摘掉彼此),回想我们之前用ZooKeeper的客户端,使用时客户端一定要尽可能多的配置ZooKeeper Server(即Leader、Follower和Observer),以防止某些ZooKeeper Server节点挂掉导致该客户端无法连接ZooKeeper集群,而且在配置ZooKeeper集群时,需要配置彼此的地址(来决定哪些能投票和选举),在Consul中不存在这样的烦恼。

Server->Server:大多数分布式的存储系统都离不开通过分区和副本解决容量和可用性的问题,Consul的Server(即Server Agent)也不例外,但Consul中没有数据分区的概念,只有数据副本,这也意味着Consul和ZooKeeper一样,同一个数据中心的Consul Server节点存储了全量的数据。细心的读者在这里会发现一个矛盾点,Consul集群底层是Gossip协议,Gossip协议构建的系统一般是AP系统,为啥我们却说Consul是CP系统?这是因为Consul的Server使用Raft协议来选主,意味着Server节点要达成一致,必须要超过半数Server节点通过才行,所以Consul本质上是一个CP系统。

在实际使用过程中,是可以不部署Client Agent的(特别是你不需要Sidecar的时候),可以通过Consul提供的SDK直连Consul Server,这是因为不管是Client Agent还是ServerAgent都提供了相同的Rest接口,就是说我们可以通过HTTP/HTTPS直接访问Client Agent或者Server Agent。

注意,Consul提供了多数据中心的支持,并且提供了跨数据中心的查询,这也是为啥Consul的官方架构图中特意显示了两个数据中心(即上图的下半部分)。

5. Consul的读一致性模式

考虑到被使用的场景不同,Consul提供了三种读一致性模型(其行为会影响KV的读取和服务发现),这三种读一致性模型如下(详见Consistency Modes | Consul by HashiCorp):

  • default- 默认几乎在所有情况下都是强一致的。但在选举新的领导者的小窗口期间,旧的领导者可能会为陈旧的值提供服务,所以此模式读取速度快但有可能读到旧值。

  • consistent- 此模式是强一致的。它要求领导者与一定数量的对等节点验证它仍然是领导者。这引入了到所有服务器节点的额外往返,由于增加了额外的往返行程而增加了延迟。大多数客户端不应该使用它,除非他们不能容忍过时的读取。

  • stale- 此模式允许任何服务器为读取提供服务,无论它是否是领导者。这意味着可以任意的读取过时的值;但是,结果通常不会落后领导者 50 毫秒。优势是非常快速和可扩展的读取,但具有更高的陈旧值的可能性。由于此模式允许在没有领导者的情况下进行读取,因此当集群不可用时仍然能够响应查询。

需要注意的是,这些模式是可以同时存在的,因为它并不是通过Consul Server的某项配置决定的,而是由客户端的请求参数决定的。

6. Consul的服务注册和健康检查

      在Consul注册服务很简单,只需要提供如下信息(详见Register Services - Service Definitions | Consul by HashiCorp): 

其实只有【-name】这个参数是必须的(-address和-port默认将使用Consul Client Agent的地址和端),而【-tag】通常用于给服务添加特殊的属性(例如该服务属于的机房或者数据中心),所以,如下最简控制台命令就通过Consul Client Agent向Consul注册了一个名叫【myApp】的服务:

consul services register -name=myApp

这里需要关注下【-meta】和【-tag】的使用,meta其实是一个Map结构,而且有诸多限制,比如我们最多能定义64个键值对,键最多为128个ASCII字符,值最多512个字符。meta更多的用于描述服务的个性化属性,这些属性在不同服务之间是没关联的,而tag的更多的是描述一些跨服务的通用属性,例如所属机房和数据中心等。当然,我们在查询服务时,即可以通过meta来筛查,也可以通过tag来筛查。

       服务发现的主要目标之一是提供可用(健康)服务的目录。为此,在服务注册时,我们可以自定义健康检查的方式,Consul针对不同的使用场景提供了多达8种的健康检查的方式(参见Monitor Services - Check Definitions | Consul by HashiCorp),我们这里列举其中四种:

  • HTTP + Interval让Consul通过GET向指定的 URL发出 HTTP请求。服务的状态取决于 HTTP 响应代码:任何2xx代码都被视为通过,429的Too ManyRequests是警告,其他任何应答码都是失败。
  • TCP + Interval:Consul将尝试通过TCP连接到指定的 IP/主机名和端口。服务的状态取决于连接尝试是否成功(即端口当前正在接受连接)。如果连接被接受,则状态为 success,否则状态为critical
  • Time to Live(TTL)这种健康检查保留给定 TTL 的最后一个已知状态,由应用自己主动上报自己的健康状态。
  • gRPC + Interval 这些检查适用于支持标准 gRPC 健康检查协议的应用程序。 

我们可以根据自己的实际情况来选择合适的健康检查机制,这也是Consul的强大之处,像ZooKeeper这种非专属的注册中心是不具备这些能力的。

7. Quick Start

为了让大家对Consul有直观的认识,本文中将演示Consul的两种核心能力的quick start,即KV存储注册中心(服务发现和注册),不管使用哪种能力,都需要部署Consul,有时间的读者可以直接跟随官网的介绍来start:Get Started | Consul - HashiCorp Learn。

如果读者本地安装了Docker环境,那么只需要在控制台输入如下命令即可部署一个可供学习或测试的Consul实例(参见Docker Hub):

docker run -d --name=dev-consul -e CONSUL_BIND_INTERFACE=eth0 consul

当然,如果本地没有安装Docker,也可以去官网下载二进制包(Downloads | Consul by HashiCorp),下载完毕后,cd到consul的目录,执行如下命令即可(-bind中写自己本地的IP即可):

consul agent -server -bootstrap -ui -data-dir /Users/xxx/Documents/consul -node=agent1 -bind=xxx.xxx.xxx.xxx

注意,因为我们要访问本地的Consul控制台,所以记得加上【-ui】这个参数。

启动成功后,访问 http://localhost:8500/ 将出现类似如下Consul控制台界面:

因为我们要演示Consul的基本功能,所以先建一个Spring Cloud工程(建Spring Cloud工程的过程这里不再阐述,参见IDE自带的Spring Cloud项目创建过程或者Spring | Spring Quickstart Guide),并且我们假定咱们的应用名称为【my-spring-cloud-consul】,即application.yml配置成如下样子:

spring:
  application:
    name: my-spring-cloud-consul
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        enabled: true
        heartbeat:
          enabled: true

注意,heartbeat需要设置成true,否则Consul会因为检查 /actuator/health 路径报404而在控制台上显示“All service checks failing”。

这里也给出该项目的pom.xml:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-all</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

7.1 Consul的Java客户端

      Consul有 ecwidorbitz 两种常见的Java客户端,本文只介绍 ecwid,请确保项目中包含如下依赖:

<dependency>
    <groupId>com.ecwid.consul</groupId>
    <artifactId>consul-api</artifactId>
    <version>1.4.5</version>
</dependency>

由于我们本地已经启动了Consul Server,那么可以在项目中写个main方法来进行测试,这里先给大家演示一个监听key/valule变化的case:

    System.out.println("开始演示KV监听机制");
    ConsulClient localhostClient = new ConsulClient("localhost:8500");

    String key = "com.my.app.foo";

    // 给key设置一个值
    localhostClient.setKVValue(key, "My Lover");

    // 获取当前key的最新值和版本(consulIndex)
    Response<GetValue> curKvValue = localhostClient.getKVValue(key);

    // 长轮训监听该key在该index后的版本变化(达到准实时感知key变化的效果)
    Response<GetValue> updateKvValue = localhostClient.getKVValue(key, new QueryParams(30000, curKvValue.getConsulIndex()));
    
    System.out.println("更新后的值:" + updateKvValue.getValue().getDecodedValue());

    System.out.println("kv watch over");

执行该程序后,可以在Consul的控制台将【com.my.app.foo】的值改掉,就可以在输出控制台看到更新后的值了。KV的操作相对比较简单,这里我们再演示一个服务注册和发现的例子,服务注册和发现的代码如下:

    ConsulClient localhostClient = new ConsulClient("localhost:8500");    
    String serviceName = "myapp";

    // register new service
    NewService newService01 = new NewService();
    newService01.setId("myapp_01");
    newService01.setName(serviceName);
    newService01.setTags(Arrays.asList("EU-West", "EU-East"));
    newService01.setPort(8080);
    localhostClient.agentServiceRegister(newService01);

    // register new service with associated health check
    NewService newService02 = new NewService();
    newService02.setId("myapp_02");
    newService02.setName(serviceName);
    newService02.setTags(Collections.singletonList("EU-East"));
    newService02.setPort(8080);

    // 添加一个健康检查
    NewService.Check serviceCheck = new NewService.Check();
    // 该地址由consul来回调检查
    serviceCheck.setHttp("http://xxx.xxx.xxx.xxx:8080/hearth/check");
    serviceCheck.setInterval("10s");
    newService02.setCheck(serviceCheck);

    localhostClient.agentServiceRegister(newService02);

    System.out.println("注册完毕!!!");

上面已经注册了一个【myapp】的服务,下面我们开始演示如何监听服务:

    ConsulClient localhostClient = new ConsulClient("localhost:8500");
    String serviceName = "myapp";

    // 基于服务名称查询所有健康的服务
    HealthServicesRequest request = HealthServicesRequest.newBuilder()
            .setPassing(true)
            .setQueryParams(QueryParams.DEFAULT)
            .build();
    Response<List<HealthService>> healthyServices = localhostClient.getHealthServices(serviceName, request);
    System.out.println(serviceName + "有" + healthyServices.getValue().size() + "个健康实例");

    // 基于某个Tag查询所有健康的服务
    HealthServicesRequest request1 = HealthServicesRequest.newBuilder()
            .setTag("EU-West")
            .setPassing(true)
            .setQueryParams(QueryParams.DEFAULT)
            .build();
    Response<List<HealthService>> healthyServices1 = localhostClient.getHealthServices("myapp", request1);
    System.out.println(serviceName + "有" + healthyServices1.getValue().size() + "个健康实例");

    // 查询所有的名为myapp的实例(包括健康检查没过的)
    Response<List<CatalogService>> myappServices = localhostClient.getCatalogService(serviceName, CatalogServiceRequest.newBuilder()
            .setQueryParams(QueryParams.DEFAULT).build());
    System.out.println(serviceName + "一共有" + myappServices.getValue().size() + "个实例");

    // 查询所有的服务(包括健康检查没过的)
    Response<Map<String, List<String>>> allServices = localhostClient.getCatalogServices(CatalogServicesRequest.newBuilder()
            .setQueryParams(QueryParams.DEFAULT).build());
    System.out.println("一共有" + allServices.getValue().size() + "个实例");
    System.out.println(JSON.toJSONString(allServices.getValue()));

    // 长轮训监听所有健康服务的变化
    Response<List<HealthService>> curHealthServices = localhostClient.getHealthServices(serviceName, HealthServicesRequest.newBuilder().build());
    Response<List<HealthService>> latestHealthServices = localhostClient.getHealthServices(serviceName, HealthServicesRequest.newBuilder()
            .setQueryParams(QueryParams.Builder.builder()
                    .setWaitTime(300000)
                    .setIndex(curHealthServices.getConsulIndex())
                    .build())
            .build());

    System.out.println("更新后的最新服务个数:" + latestHealthServices.getValue().size());

其实我们不难发现,不管是KV还是服务发现,Consul都提供了【长轮训+版本】来监听变化的机制。

7.2 KV存储Quick Start

接下面我们演示Spring Cloud项目如何使用Consul,先看看KV存储,需要注意一点,Consul的目标并不是成为一个旗舰型的配置系统或者KV高速存储系统,所以请不要把Consul当做Apollo或者Redis来使用,Consul的目标是管理分布式系统的少量应用配置

本文中将展示如何通过一个Spring应用来获取Consul的KV配置,并且我们在Consul控制台修改该配置后,Spring应用能获取到最新的配置。话不多说我们立马开始,我们点击Consul控制台左侧的【Key/Value】,新加一个名为【config/my-spring-cloud-consul/abc】的变量,其值为【my lover】,如下图:

 需要注意的是,如果想在Spring Cloud应用中读取到对应的KV配置,那么这个Key的前缀一定是【config/[Spring应用名称/]】。点击【Save】按钮保存后,这个KV配置就创建成功了。

那么我们在Spring Cloud中如何读取该配置呢?直接Show代码吧:

@RefreshScope
@RestController
@RequestMapping("/mzz")
public class HomeController {

    /**
     * 参见{@link org.springframework.cloud.consul.config.ConfigWatch}
     */
    @Value("${abc}")
    private String abc = "abc";

    @RequestMapping("/getLatestAbc")
    public String getLatestAbc() {
        return abc;
    }
}

可以看出,我们在控制器中定义了一个abc的变量(正好和Consul中的config/my-spring-cloud-consul/abc对应),启动该Spring Cloud应用后,我们访问 http://localhost:8080/mzz/getLatestAbc 就可以看到返回abc的最新值了,如果你在Consul控制台中修改config/my-spring-cloud-consul/abc的值,重新访问 http://localhost:8080/mzz/getLatestAbc 可以发现能返回修改后的值(注意,一定要使用@RefreshScope)。

7.3 服务注册发现Quick Start

使用Spring Cloud Consul进行服务注册很简单,只要在我们启动类上打上一个@EnableDiscoveryClient注解即可(新版本已经将这个注解废弃),如下:

@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudConsulApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudConsulApplication.class, args);
    }
}

启动后,我们就可以在Consul控制台看到如下信息:

说明服务注册成功!! 

8. Spring Cloud Commons 中的服务注册和发现

Spring Cloud Commons 以两个库的形式提供功能:Spring Cloud Context 和 Spring Cloud Commons。Spring Cloud Context 为 Spring Cloud 应用程序的 ApplicationContext 提供实用程序和特殊服务(引导上下文、加密、刷新范围和环境端点)。Spring Cloud Commons 是一组抽象和通用类,用于不同的 Spring Cloud 实现(例如 Spring Cloud Netflix 与 Spring Cloud Consul)。

为啥突然提到Spring Cloud Commons?Spring Cloud Commons 是 Spring Cloud 核心基础库类,而SCC的服务发现和注册和 Spring Cloud Commons 中的 spring-cloud-commons 库实现息息相关。

spring-cloud-commons 库主要包含三个特性(摘自官网):

  • 服务发现客户端 DiscoveryClient 接口

  • 服务注册 ServiceRegistry 接口

  • 用服务发现客户端(DiscoveryClient)解析主机名的 RestTemplate 实现(其中包含LoadBalance的实现)

8.1 服务发现DiscoveryClient

我们先来看下 DiscoveryClient 接口的定义:
public interface DiscoveryClient extends Ordered {

	int DEFAULT_ORDER = 0;

	String description();

	List<ServiceInstance> getInstances(String serviceId);

	List<String> getServices();

	default void probe() {
		getServices();
	}

	@Override
	default int getOrder() {
		return DEFAULT_ORDER;
	}
}

(为了减少行数,去掉了注释,有兴趣的读者还可以去看看 ServiceInstance 接口的定义)可以看到其核心方法就是通过服务ID(serviceId)来返回该服务的所有实例(一般是返回健康可用的实例)列表,如果你是要实现服务发现的能力,只要你只要实现DiscoveryClient 接口,并将该实现类通过Spring Boot的Auto-configuration机制注入到Spring容器中,那么你的服务发现能力就能被(例如给LoadBalance)使用。所以,如果你想从一个注册中心中找可用的服务,那么你可以这样用:

public class SomeLoadBalance {

	@Autowire
	private DiscoveryClient discoveryClient;

    ... ...
}

那如果我有多个注册中心呢?别忘了 DiscoveryClient 继承自 Ordered,我们可以自定义各个注册中心的 DiscoveryClient 实现类的顺序,所以如果是多个注册中心,那么我们可以这么用:

public class SomeLoadBalance {

	@Autowire
	private List<DiscoveryClient> discoveryClientList;

    ... ...
}

Spring会默认把 getOrder() 值较小(优先级较高)的放在列表中的前面,然后可以通过优先级来找某个服务的实例,例如当我们有两个机房A(主)和B(备),A机房的应用优先调用A机房的基础服务(即同机房调用),但A机房的应用为了容灾还连接了B机房的基础服务,我们可以把A机房的 DiscoveryClient 实例优先级调整的比B机房的DiscoveryClient高(即A机房的DiscoveryClient 实例返回的 order 值比B机房的小),这样一旦A机房的基础服务可用,A机房的应用就不会调到B机房的基础服务,而如果A机房的基础服务出现故障,那么从A机房的基础服务中就无法找到可用的,我们可以让其去寻找B机房的基础服务。

如果只是简单的服务发现,spring-cloud-commons 提供了 DiscoveryClient 接口的基础实现类 SimpleDiscoveryClient,有了 SimpleDiscoveryClient 我们就可以通过配置文件来配置服务发现了,如何配置参见:Cloud Native Applications

8.2 服务注册ServiceRegistry

我们接下来再聊聊服务注册,让我们看看 ServiceRegistry 接口的定义:

public interface ServiceRegistry<R extends Registration> {

	void register(R registration);

	void deregister(R registration);

	void close();

	void setStatus(R registration, String status);

	<T> T getStatus(R registration);
}

可以看到,该泛型接口可以注册一个 Registration 接口的实现类的对象,而这个 Registration 其实和前面说的服务发现接口(DiscoveryClient)中用到的服务实例接口 ServiceInstance 有着非常紧密的联系:

public interface Registration extends ServiceInstance {

}

ServiceRegistry 接口包含了注册、注销等核心能力的定义,如果要实现自定义服务注册的能力,方法和实现自定义服务发现一样,通过 Auto-configuration 机制即可,这里不再阐述。

这里还有个问题没有解释,为啥我们能做到一启动应用就自动将自己注册(要关闭默认的自动注册行为可以设置 @EnableDiscoveryClient(autoRegister=false) 或者 spring.cloud.service-registry.auto-registration.enabled 设置成 false)为了对服务注册进行生命周期管理,spring-cloud-commons 提供了抽象类 AbstractAutoServiceRegistration,AbstractAutoServiceRegistration 实现了 ApplicationListener<WebServerInitializedEvent> 接口,意味着只要实现了它的类(例如 SCC 中的 ConsulAutoServiceRegistration),默认会在Web容器启动后调用 AbstractAutoServiceRegistration#start() 方法来注册本地服务,眼见为实(省略了无关代码):

public abstract class AbstractAutoServiceRegistration<R extends Registration>
		implements AutoServiceRegistration, ApplicationContextAware, ApplicationListener<WebServerInitializedEvent> {

	@Override
	public void onApplicationEvent(WebServerInitializedEvent event) {
		bind(event);
	}

	public void bind(WebServerInitializedEvent event) {
		ApplicationContext context = event.getApplicationContext();
		if (context instanceof ConfigurableWebServerApplicationContext) {
			if ("management".equals(((ConfigurableWebServerApplicationContext) context).getServerNamespace())) {
				return;
			}
		}
		this.port.compareAndSet(0, event.getWebServer().getPort());
		this.start();
	}

	public void start() {
		if (!isEnabled()) {
			return;
		}

		// only initialize if nonSecurePort is greater than 0 and it isn't already running
		// because of containerPortInitializer below
		if (!this.running.get()) {
			this.context.publishEvent(new InstancePreRegisteredEvent(this, getRegistration()));
			register();
			if (shouldRegisterManagement()) {
				registerManagement();
			}
			this.context.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));
			this.running.compareAndSet(false, true);
		}
	}

    // 最终在这里进行了服务注册
	protected void registerManagement() {
		R registration = getManagementRegistration();
		if (registration != null) {
			this.serviceRegistry.register(registration);
		}
	}
}

9. Spring Cloud Consul 实现原理

前面说了这么多,现在总算轮到我们开始讨论SCC的原理了。

9.1 SCC的自动注入

       我们知道,要和Spring Boot应用打通,最常用的方式就是Auto-configuration,SCC也不例外,其 spring-cloud-starter-consul-discovery 模块主要就是干这个事情,需要注意的是,如果按照官方文档(Spring Cloud Consul)说的只依赖 spring-cloud-starter-consul-discovery 是没开启Consul的KV配置能力的,因为配置能力在 spring-cloud-starter-consul-config 模块中,所以如果嫌麻烦,我们可以在项目中直接依赖 spring-cloud-starter-consul-all 这个jar!

9.2 SCC应用配置原理

当我们依赖 spring-cloud-starter-consul-config 时,主要是依赖 spring-cloud-consul-config 这模块,老规矩,我们从 spring.factories 入手:

# Auto Configuration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.consul.config.ConsulConfigAutoConfiguration
# Bootstrap Configuration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.consul.config.ConsulConfigBootstrapConfiguration

我们一眼就看出核心关键是 ConsulConfigAutoConfiguration,其实现如下:

@Configuration
@ConditionalOnConsulEnabled
@ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", matchIfMissing = true)
public class ConsulConfigAutoConfiguration {

	public static final String CONFIG_WATCH_TASK_SCHEDULER_NAME = "configWatchTaskScheduler";

	@Configuration
	@ConditionalOnClass(RefreshEndpoint.class)
	protected static class ConsulRefreshConfiguration {

		@Bean
		@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", matchIfMissing = true)
		public ConfigWatch configWatch(ConsulConfigProperties properties,
				ConsulPropertySourceLocator locator, ConsulClient consul,
				@Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
			return new ConfigWatch(properties, consul, locator.getContextIndexes(),
					taskScheduler);
		}

		@Bean(name = CONFIG_WATCH_TASK_SCHEDULER_NAME)
		@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", matchIfMissing = true)
		public TaskScheduler configWatchTaskScheduler() {
			return new ThreadPoolTaskScheduler();
		}
	}
}

同样,我们可以通过将总开关 spring.cloud.consul.config.enabled 设置成 false 来关闭该功能,配置更新被后的原理是SCC使用Consul的Java SDK来进行长轮训Watch配置的变更,以保证配置能实时更新,但需要注意的一点是,如果要保证配置变更的实时感知,ConfigWatch 中用到的两个配置需要额外关注,即定时任务的间隔时间 spring.cloud.consul.config.watch.delay(默认1000ms)要足够小,长轮训等待时间 spring.cloud.consul.config.watch.waitTime (默认55s) 可以配置的长一点(保持默认即可),因为用的是 scheduleWithFixedDelay,所以极端情况下配置更新了最长在 spring.cloud.consul.config.watch.delay 内无法感知。

有兴趣的读者可以去看:org.springframework.cloud.consul.config.ConfigWatch的实现,这里不再阐述。

9.3 SCC服务注册原理

spring-cloud-starter-consul-discovery 主要目的之一就是依赖 spring-cloud-consul-discovery ,而 spring-cloud-consul-discovery 模块的 spring.factories 文件内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.consul.discovery.RibbonConsulAutoConfiguration,\
org.springframework.cloud.consul.discovery.configclient.ConsulConfigServerAutoConfiguration,\
org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationAutoConfiguration,\
org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistryAutoConfiguration,\
org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration,\
org.springframework.cloud.consul.discovery.ConsulCatalogWatchAutoConfiguration, \
org.springframework.cloud.consul.support.ConsulHeartbeatAutoConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.consul.discovery.configclient.ConsulDiscoveryClientConfigServiceBootstrapConfiguration

我们先来看看和服务注册相关的两个AutoConfiguration,即 ConsulServiceRegistryAutoConfiguration 和 ConsulAutoServiceRegistrationAutoConfiguration,直接show code,先看 ConsulServiceRegistryAutoConfiguration 的实现:

@Configuration
@ConditionalOnConsulEnabled // spring.cloud.consul.enabled 不为false且存在ConsulClient类
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true)
@AutoConfigureBefore(ServiceRegistryAutoConfiguration.class)
public class ConsulServiceRegistryAutoConfiguration {

	/**
	 * 如果没有 ConsulServiceRegistry 实例则创建, ConsulServiceRegistry 实例包含Consul客户端ConsulClient、
	 * spring.cloud.consul.discovery 配置类 ConsulDiscoveryProperties、
	 * spring.cloud.consul.discovery.heartbeat 配置类 HeartbeatProperties 等
	 */
	@Bean
	@ConditionalOnMissingBean
	public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient,
			ConsulDiscoveryProperties properties, HeartbeatProperties heartbeatProperties,
			@Autowired(required = false) TtlScheduler ttlScheduler) {
		return new ConsulServiceRegistry(consulClient, properties, ttlScheduler,
				heartbeatProperties);
	}

	/**
	 * 如果没有 HeartbeatProperties 实例则创建,上面 consulServiceRegistry 方法的入参之一
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean
	public HeartbeatProperties heartbeatProperties() {
		// 注意,默认HeartbeatProperties#ttlValue 是30秒(因为Consul的健康检查的TTL模式默认就30秒),但并不意味着我们主动上报心跳间隔是30秒(你不可能去踩点),
		// 所以这里SCC有自己的算法,默认会20秒上报一次(参见HeartbeatProperties#computeHearbeatInterval())
		return new HeartbeatProperties();
	}

	/**
	 * 如果没有 ConsulDiscoveryProperties 实例则创建,上面 consulServiceRegistry 方法的入参之一。
	 * 注意,这里 ConsulDiscoveryProperties 虽然说的是服务发现的配置,但也包含服务注册的配置,包含服务名称、健康检查的路径、
	 * Consul的ACL指令(因为Consul支持授权访问)等重要信息。
	 * 之所以要把 InetUtils 作为入参,是因为Consul默认是去连本地的Consul Client Agent,所以需要填一个本地的非环路IP地址
	 */
	@Bean
	@ConditionalOnMissingBean
	public ConsulDiscoveryProperties consulDiscoveryProperties(InetUtils inetUtils) {
		return new ConsulDiscoveryProperties(inetUtils);
	}
}

从代码可以看出,ConsulServiceRegistryAutoConfiguration 构建了心跳、服务发现配置和服务注册(含服务发现)的三个Bean,而且仅仅在 spring.cloud.consul.enabled 和 spring.cloud.service-registry.enabled 不为false且存在ConsulClient类时才去自动装配。其中的 TtlScheduler 入参就是TTL的定时任务实现。

而需要注意的一点是,该 AutoConfiguration 是在 ServiceRegistryAutoConfiguration 之前来构建的(因为有@AutoConfigureBefore),这是因为 ServiceRegistryAutoConfiguration 是 spring-cloud-common 中用来自动装载所有ServiceRegistry的,所以需要在它之前先把Consul的ServiceRegistry构建出来,这也是为什么要拆成 ConsulServiceRegistryAutoConfiguration 和 ConsulAutoServiceRegistrationAutoConfiguration 两个 AutoConfiguration 的原因。 

看完 ConsulServiceRegistryAutoConfiguration 后我们接下来看看 ConsulAutoServiceRegistrationAutoConfiguration 做了什么事情:

@Configuration
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnMissingBean(type = "org.springframework.cloud.consul.discovery.ConsulLifecycle")
@ConditionalOnConsulEnabled // 这里和 ConsulServiceRegistryAutoConfiguration 保持一致
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
		ConsulServiceRegistryAutoConfiguration.class })
public class ConsulAutoServiceRegistrationAutoConfiguration {

	@Autowired
	AutoServiceRegistrationProperties autoServiceRegistrationProperties;

	/**
	 * 还记得之前提到的,为了做到启动时自动注册本应用,
	 * ConsulAutoServiceRegistration 实现了 spring-cloud-commons 的 AbstractAutoServiceRegistration,
	 * 需要注意的是,ConsulAutoServiceRegistration 屏蔽了 AbstractAutoServiceRegistration 的 bind(),
	 * 所以监听 WebServer启动成功后是由另一个类(即下面的 ConsulAutoServiceRegistrationListener )来做的
	 */
	@Bean
	@ConditionalOnMissingBean
	public ConsulAutoServiceRegistration consulAutoServiceRegistration(
			ConsulServiceRegistry registry,
			AutoServiceRegistrationProperties autoServiceRegistrationProperties,
			ConsulDiscoveryProperties properties,
			ConsulAutoRegistration consulRegistration) {
		return new ConsulAutoServiceRegistration(registry,
				autoServiceRegistrationProperties, properties, consulRegistration);
	}

	/**
	 *  ConsulAutoServiceRegistrationListener 中通过监听容器消息来负责启动 ConsulAutoServiceRegistration 注册本地服务
	 */
	@Bean
	public ConsulAutoServiceRegistrationListener consulAutoServiceRegistrationListener(
			ConsulAutoServiceRegistration registration) {
		return new ConsulAutoServiceRegistrationListener(registration);
	}

	@Bean
	@ConditionalOnMissingBean
	public ConsulAutoRegistration consulRegistration(
			AutoServiceRegistrationProperties autoServiceRegistrationProperties,
			ConsulDiscoveryProperties properties, ApplicationContext applicationContext,
			ObjectProvider<List<ConsulRegistrationCustomizer>> registrationCustomizers,
			ObjectProvider<List<ConsulManagementRegistrationCustomizer>> managementRegistrationCustomizers,
			HeartbeatProperties heartbeatProperties) {
		return ConsulAutoRegistration.registration(autoServiceRegistrationProperties,
				properties, applicationContext, registrationCustomizers.getIfAvailable(),
				managementRegistrationCustomizers.getIfAvailable(), heartbeatProperties);
	}

	@Configuration
	@ConditionalOnClass(ServletContext.class)
	protected static class ConsulServletConfiguration {
		@Bean
		public ConsulRegistrationCustomizer servletConsulCustomizer(
				ObjectProvider<ServletContext> servletContext) {
			return new ConsulServletRegistrationCustomizer(servletContext);
		}
	}
}

这里我们也可以发现,当spring.cloud.service-registry.auto-registration.enabled 为 false 时,就不会去自动注册自己的服务了。

那么,SCC在启动时往Consul Server 注册了哪些内容?根据我们之前的分析,SCC肯定有 Registration 的实现,即 ConsulRegistrationConsulAutoRegistration,其中 ConsulAutoRegistration 又是 ConsulRegistration 的子类,ConsulAutoRegistration#registration() 方法实现如下:

	public static ConsulAutoRegistration registration(
			AutoServiceRegistrationProperties autoServiceRegistrationProperties,
			ConsulDiscoveryProperties properties, ApplicationContext context,
			List<ConsulRegistrationCustomizer> registrationCustomizers,
			List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
			HeartbeatProperties heartbeatProperties) {

		// 这是ecwid注册服务的标准类
		NewService service = new NewService();
		// 获取服务注册的名称,如果没配置 spring.cloud.consul.discovery.serviceName,那么就取应用名称(spring.application.name)
		String appName = getAppName(properties, context.getEnvironment());
		service.setId(getInstanceId(properties, context));
		// 如果配置的不是取本地Agent的地址,则取配置的地址
		if (!properties.isPreferAgentAddress()) {
			service.setAddress(properties.getHostname());
		}
		service.setName(normalizeForDns(appName));
		// 解析tag,包括zone、group和http/https
		service.setTags(createTags(properties));

		if (properties.getPort() != null) {
			service.setPort(properties.getPort());
			// 设置健康检查和心跳
			setCheck(service, autoServiceRegistrationProperties, properties, context,
					heartbeatProperties);
		}

		ConsulAutoRegistration registration = new ConsulAutoRegistration(service,
				autoServiceRegistrationProperties, properties, context,
				heartbeatProperties, managementRegistrationCustomizers);
		// 对自定义的 ConsulRegistrationCustomizer 操作一波,我们可以通过实现 ConsulRegistrationCustomizer 接口来添加额外的自定义信息
		customize(registrationCustomizers, registration);
		return registration;
	}

	public static String getAppName(ConsulDiscoveryProperties properties,
			Environment env) {
		final String appName = properties.getServiceName();
		if (StringUtils.hasText(appName)) {
			return appName;
		}
		return env.getProperty("spring.application.name", "application");
	}

从上述代码可知,我们可以通过实现 ConsulRegistrationCustomizer 接口并注入到Spring容器中来增加我们注册前的自定义行为,比如新增我们自己的tag或者meta数据, ConsulRegistrationCustomizer 实现如下:

public interface ConsulRegistrationCustomizer {
	void customize(ConsulRegistration registration);
}

可以看到入参是 ConsulRegistration 对象,你可以为所欲为了。

9.4 SCC服务发现原理

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.consul.discovery.RibbonConsulAutoConfiguration,\
org.springframework.cloud.consul.discovery.configclient.ConsulConfigServerAutoConfiguration,\
org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration,\
org.springframework.cloud.consul.discovery.ConsulCatalogWatchAutoConfiguration, \

这是前面出现过的 spring-cloud-consul-discovery 的 spring.factories 文件的部分内容,可以看出和服务发现相关的是4个 AutoConfiguration,我们重点看看 ConsulDiscoveryClientConfiguration 和  ConsulCatalogWatchAutoConfiguration 两个 AutoConfiguration。 

ConsulDiscoveryClientConfiguration 的代码量很少,它主要是构造 ConsulDiscoveryClient,ConsulDiscoveryClient 里面包装了 ecwid 的 ConsulClient,代码如下:

public class ConsulDiscoveryClient implements DiscoveryClient {

	private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);

	private final ConsulClient client;

	private final ConsulDiscoveryProperties properties;

    ... ...
}

还记得咱们之前聊到的 spring-cloud-commons 中的服务发现扩展接口 DiscoveryClient 吗?ConsulDiscoveryClient 就是其实现类,那我们直接看看 ConsulDiscoveryClient 的实现吧:

public class ConsulDiscoveryClient implements DiscoveryClient {

	private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);

	private final ConsulClient client;

	private final ConsulDiscoveryProperties properties;

	public ConsulDiscoveryClient(ConsulClient client,
			ConsulDiscoveryProperties properties) {
		this.client = client;
		this.properties = properties;
	}

	@Override
	public String description() {
		return "Spring Cloud Consul Discovery Client";
	}

	@Override
	public List<ServiceInstance> getInstances(final String serviceId) {
		return getInstances(serviceId, QueryParams.DEFAULT);
	}

	public List<ServiceInstance> getInstances(final String serviceId,
			final QueryParams queryParams) {
		List<ServiceInstance> instances = new ArrayList<>();
		addInstancesToList(instances, serviceId, queryParams);
		return instances;
	}

	private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
			QueryParams queryParams) {
		// Consul支持访问权限控制
		String aclToken = this.properties.getAclToken();
		Response<List<HealthService>> services;
		if (StringUtils.hasText(aclToken)) {
			services = this.client.getHealthServices(serviceId,
					this.properties.getDefaultQueryTag(),
					this.properties.isQueryPassing(), queryParams, aclToken);
		} else {
			// 这里和前面演示的ecwid例子类似,只查询健康的服务
			services = this.client.getHealthServices(serviceId,
					this.properties.getDefaultQueryTag(),
					this.properties.isQueryPassing(), queryParams);
		}

		for (HealthService service : services.getValue()) {
			String host = findHost(service);

			Map<String, String> metadata = getMetadata(service);
			boolean secure = false;
			if (metadata.containsKey("secure")) {
				secure = Boolean.parseBoolean(metadata.get("secure"));
			}

			// DefaultServiceInstance 是 spring-cloud-commons中 ServiceInstance 接口的默认实现
			instances.add(new DefaultServiceInstance(service.getService().getId(),
					serviceId, host, service.getService().getPort(), secure, metadata));
		}
	}

	public List<ServiceInstance> getAllInstances() {
		List<ServiceInstance> instances = new ArrayList<>();

		Response<Map<String, List<String>>> services = this.client
				.getCatalogServices(QueryParams.DEFAULT);
		for (String serviceId : services.getValue().keySet()) {
			addInstancesToList(instances, serviceId, QueryParams.DEFAULT);
		}
		return instances;
	}

	@Override
	public List<String> getServices() {
		String aclToken = this.properties.getAclToken();

		if (StringUtils.hasText(aclToken)) {
			return new ArrayList<>(
					this.client.getCatalogServices(QueryParams.DEFAULT, aclToken)
							.getValue().keySet());
		} else {
			// 这里查询所有的服务ID
			return new ArrayList<>(this.client.getCatalogServices(QueryParams.DEFAULT)
					.getValue().keySet());
		}
	}

	@Override
	public int getOrder() {
		// 别忘了前面说的服务发现的顺序(优先级),这里SCC做成了可配置的(spring.cloud.consul.discovery.order)
		return this.properties.getOrder();
	}
}

整体实现非常的简单,这里不做过多阐述。

接下来是 ConsulCatalogWatchAutoConfiguration,该 AutoConfiguration 实现如下:

@Configuration
@ConditionalOnConsulEnabled
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.catalog-services-watch.enabled", matchIfMissing = true)
@ConditionalOnDiscoveryEnabled
@AutoConfigureAfter({ ConsulDiscoveryClientConfiguration.class })
public class ConsulCatalogWatchAutoConfiguration {

	/**
	 * Name of the catalog watch task scheduler bean.
	 */
	public static final String CATALOG_WATCH_TASK_SCHEDULER_NAME = "catalogWatchTaskScheduler";

	@Bean
	@ConditionalOnMissingBean
	public ConsulCatalogWatch consulCatalogWatch(
			ConsulDiscoveryProperties discoveryProperties, ConsulClient consulClient,
			@Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
		return new ConsulCatalogWatch(discoveryProperties, consulClient, taskScheduler);
	}

	@Bean(name = CATALOG_WATCH_TASK_SCHEDULER_NAME)
	public TaskScheduler catalogWatchTaskScheduler() {
		return new ThreadPoolTaskScheduler();
	}
}

可以发现其实现和之前讲配置时提到的 ConsulConfigAutoConfiguration 很像核心就是构造 ConsulCatalogWatch,当然我们可以通过将 spring.cloud.consul.discovery.catalog-services-watch.enabled 设置成 false 来关闭该功能,ConsulCatalogWatch 顾名思义就是用来监控(服务)目录的,ConsulCatalogWatch 内部会初始化一个定时任务来长轮训监听所有服务的变化,并将该变化通过Spring的Event发出来,其实现如下:

public class ConsulCatalogWatch
		implements ApplicationEventPublisherAware, SmartLifecycle {

	private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);

	private final ConsulDiscoveryProperties properties;

	private final ConsulClient consul;

	private final TaskScheduler taskScheduler;

	private final AtomicReference<BigInteger> catalogServicesIndex = new AtomicReference<>();

	private final AtomicBoolean running = new AtomicBoolean(false);

	private ApplicationEventPublisher publisher;

	private ScheduledFuture<?> watchFuture;

	public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul) {
		this(properties, consul, getTaskScheduler());
	}

	public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul,
			TaskScheduler taskScheduler) {
		this.properties = properties;
		this.consul = consul;
		this.taskScheduler = taskScheduler;
	}

	private static ThreadPoolTaskScheduler getTaskScheduler() {
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.initialize();
		return taskScheduler;
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}

	@Override
	public boolean isAutoStartup() {
		return true;
	}

	@Override
	public void stop(Runnable callback) {
		this.stop();
		callback.run();
	}

	@Override
	public void start() {
		if (this.running.compareAndSet(false, true)) {
			// 启动定时任务,可以通过 spring.cloud.consul.discovery.catalogServicesWatchDelay 修改定时任务间隔时间,默认是1000ms
			this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(
					this::catalogServicesWatch,
					this.properties.getCatalogServicesWatchDelay());
		}
	}

	@Override
	public void stop() {
		if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
			this.watchFuture.cancel(true);
		}
	}

	@Override
	public boolean isRunning() {
		return false;
	}

	@Override
	public int getPhase() {
		return 0;
	}

	@Timed("consul.watch-catalog-services")
	public void catalogServicesWatch() {
		try {
			long index = -1;
			if (this.catalogServicesIndex.get() != null) {
				// 查询之前已经执行过,那直接取出上次监听的版本
				index = this.catalogServicesIndex.get().longValue();
			}

			// 长轮训某个版本之后的所有服务变更
			Response<Map<String, List<String>>> response = this.consul.getCatalogServices(
					// 这里我们可以通过 spring.cloud.consul.discovery.catalogServicesWatchTimeout 配置长轮训时间,默认是2s
					new QueryParams(this.properties.getCatalogServicesWatchTimeout(),
							index),
					this.properties.getAclToken());
			Long consulIndex = response.getConsulIndex();
			if (consulIndex != null) {
				this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
			}
			
			// 你没看错,仅仅是将该服务变更事件通过消息发布出去,SCC内部并没有处理该消息
			this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
		} catch (Exception e) {
			log.error("Error watching Consul CatalogServices", e);
		}
	}
}

仅仅是为了在服务发生变更时发布 HeartbeatEvent ?需要知道的是,这个 HeartbeatEvent 在SCC 和 spring-cloud-commons 内部都是没有消费的,特意翻了下 ConsulCatalogWatch 的提交记录:

果然,主要是给 Zuul 这种上游框架对服务变更做出反应用的,记住一点,这里只是把变更的版本通知出去了,至于变更内容是什么还是需要上游框架去拉一次的。还有,如果真要做到实时通知,spring.cloud.consul.discovery.catalogServicesWatchDelay(默认1000毫秒) 的值要配置的足够小,而 spring.cloud.consul.discovery.catalogServicesWatchTimeout(默认2秒) 的值,因为用的是 scheduleWithFixedDelay,所以极端情况下配置更新了最长在 spring.cloud.consul.discovery.catalogServicesWatchDelay 内无法感知。

10. 总结

本文较详细的介绍了Consul、Spring Cloud Commons 和 SCC 之间的关系以及 SCC 的实现原理,希望读者能有所收获,如果有阐述有误的地方也欢迎指正。

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值