目录

spirngcloud服务注册与发现consul

Consul简介

Consul 官网:https://www.consul.io/intro/index.html。Consul 是一套 开源的 分布式服务发现和配置管理系统,由 HashiCorp 公司用 Go语言 开发的。

Consul 提供了微服务系统中的 服务治理配置中心控制总线 等功能。这些功能中的每一个都可以根据需求来单独使用,也可以一起使用来构建全方位的服务网格,总之 Consul 提供了一整套完整的服务网格化解决方案。

下载地址:https://www.consul.io/downloads.html

附:Spring Cloud Consul 中文文档参考手册:https://www.springcloud.cc/spring-cloud-consul.html

Consul核心功能

20201108134417

优点

  1. 基于 Raft 协议,比较简洁
  2. 支持健康检查
  3. 同时支持 HTTP 和 DNS 协议两种服务发现方式
  4. 支持 K-V 键值存储(类似于 Redis)
  5. 支持多数据中心
  6. 提供了可视化的 web 管理界面
  7. 支持 Linux、Mac、Windows

安装并运行Consul

官方演示动画mac篇

  1. 解压

    1
    
    $ unzip consul_1.8.4_darwin_amd64.zip
    
  2. 移动到可执行目录

    1
    
    $ mv consul /usr/local/bin
    
  3. 验证

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    
    $ consul -v
    Consul v1.8.4
    Revision 12b16df32
    Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
    $ consul
    Usage: consul [--version] [--help] <command> [<args>]
       
    Available commands are:
        acl            Interact with Consul's ACLs
        agent          Runs a Consul agent
        catalog        Interact with the catalog
        config         Interact with Consul's Centralized Configurations
        connect        Interact with Consul Connect
        debug          Records a debugging archive for operators
        event          Fire a new event
        exec           Executes a command on Consul nodes
        force-leave    Forces a member of the cluster to enter the "left" state
        info           Provides debugging information for operators.
        intention      Interact with Connect service intentions
        join           Tell Consul agent to join cluster
        keygen         Generates a new encryption key
        keyring        Manages gossip layer encryption keys
        kv             Interact with the key-value store
        leave          Gracefully leaves the Consul cluster and shuts down
        lock           Execute a command holding a lock
        login          Login to Consul using an auth method
        logout         Destroy a Consul token created with login
        maint          Controls node or service maintenance mode
        members        Lists the members of a Consul cluster
        monitor        Stream logs from a Consul agent
        operator       Provides cluster-level tools for Consul operators
        reload         Triggers the agent to reload configuration files
        rtt            Estimates network round trip time between nodes
        services       Interact with services
        snapshot       Saves, restores and inspects snapshots of Consul server state
        tls            Builtin helpers for creating CAs and certificates
        validate       Validate config files/directories
        version        Prints the Consul version
        watch          Watch for changes in Consul
    
  4. 运行consul

    1
    
    $ consul agent -dev
    
  5. 访问consul控制界面 localhost:8500

    http://img.cana.space/picStore/20201108135811.png

服务提供者

  1. 新建cloud-provider-consul-payment8006,拷贝cloud-provider-payment8004进行修改

  2. pom

    1
    2
    3
    4
    5
    
     <!--SpringBoot整合consul-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-consul-discovery</artifactId>
            </dependency>
    
  3. yml

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    server:
      port: 8006
       
    spring:
      application:
        name: cloud-payment-consul-service
      cloud:
        consul:
          host: localhost
          port: 8500
          discovery:
            service-name: ${spring.application.name}
    
  4. 主启动类

    一样,增加注解@EnableDiscoveryClient

  5. 业务类controller

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    @RestController
    @Slf4j
    public class PaymentController {
       
       
        @Value("${server.port}")
        private String serverPort;
       
        @GetMapping("/payment/consul")
        public String paymentZK() {
            return "spring cloud with consul: " + serverPort + "\t" + UUID.randomUUID().toString();
        }
    }
    
  6. 验证

    1. 访问

      GET http://localhost:8006/payment/consul

    2. 查看注册中心服务者列表变化

      http://img.cana.space/picStore/20201108141206.png

    3. 可以点进服务里面查看健康信息

      http://img.cana.space/picStore/20201108141326.png

服务消费者

  1. 新建cloud-consumer-consul-order80,拷贝cloud-provider-consul-payment8006进行修改

  2. 改pom

    同cloud-provider-consul-payment8006

  3. yml

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    server:
      port: 80
       
    spring:
      application:
        name: cloud-consumer-consul-service
      cloud:
        consul:
          host: localhost
          port: 8500
          discovery:
            service-name: ${spring.application.name}
    
  4. 主启动

    也是一样,增加注解@EnableDiscoveryClient

  5. 业务类controller

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    @RestController
    @Slf4j
    public class OrderConsumerController {
       
        private final static String PAYMENT_URL = "http://cloud-payment-consul-service";
       
        private final RestTemplate restTemplate;
       
        public OrderConsumerController(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }
       
       
        @Value("${server.port}")
        private String serverPort;
       
        @GetMapping("/order/payment")
        public String getPaymentById() {
            return restTemplate.getForObject(PAYMENT_URL + "/payment/consul", String.class);
        }
    }
    
  6. 验证

    1. 访问GET http://localhost:80/order/payment/

    2. 查看注册中心服务列表变化

      http://img.cana.space/picStore/20201108142535.png

三个注册中心异同点

http://img.cana.space/picStore/20201108143821.png