Consul detailed tutorial (SpringBoot case)

A brief introduction and basic use of Consul

A brief introduction to Consul

Consul is a Google open source service discovery and configuration management center service developed using the Go language. It has built-in service registration and discovery framework, distributed consistency protocol implementation, health check, Key/Value storage, and multi-data center solutions, and no longer needs to rely on other tools (such as ZooKeeper, etc.). Service deployment is simple, with only a runnable binary package. Each node needs to run an agent, which has two operating modes: server and client. It is officially recommended that each data center requires 3 or 5 server nodes to ensure data security and ensure that the server-leader election can be carried out correctly.

👀️ https://www.consul.io/intro/index.html

Functions of Consul

  • client
    CLIENT represents the client mode of consul, which is the client mode. It is a mode of consul node. In this mode, all services registered to the current node will be forwarded to SERVER, and the information itself will not be persisted.
  • server
  • SERVER represents the server mode of consul, indicating that this consul is a server. In this mode, the functions are the same as CLIENT. The only difference is that it will persist all information locally, so that in the event of a failure, the information can be retained. of.
  • server-leader
    The middle SERVER has the word LEADER under it, indicating that this SERVER is their boss. What is different from other SERVERs is that it needs to be responsible for synchronizing registered information to other SERVERs, and is also responsible for health monitoring of each node.
  • raft
    To ensure data consistency between server nodes, the consistency protocol uses raft, while zookeeper uses paxos and etcd also uses raft.
  • service discovery protocol
    consul uses http and dns protocols, etcd only supports http
  • Service registration
    Consul supports two ways to realize service registration. One is to register the http API through the consul service, and the service itself calls the API to realize the registration. The other way is to realize the registration through a json configuration file, and the service that needs to be registered is registered in json. The format configuration file is given. Consul officially recommends using the second method.
  • service discovery
    Consul supports two ways to realize service discovery. One is to query which services are available through the http API, and the other is to use the DNS (port 8600) that comes with the consul agent. The domain name is given in the form of NAME.service.consul. NAME is the name of the service in the defined service configuration file. The DNS method can check the service through check.
  • Communication protocol between services
    Consul uses the gossip protocol to manage membership relationships and broadcast messages to the entire cluster. It has two gossip pools (LAN pool and WAN pool). The LAN pool is for internal communication in the same data center, and the WAN pool is for communication between multiple data centers. LAN There are multiple pools, but there is only one WAN pool.

Download and install Consul

Open Consul official website

https://www.consul.io/downloads

  1. Select the system for installation (here we demonstrate using windows)

Insert image description here

  1. After downloading/decompressing/you will get a file of consul.exe

![Insert image description here](https://img-blog.csdnimg.cn/direct/6993e17cf60e4f47be9281f99e4a06d6.png

  1. Open the cmd window in the consul.exe command
    3.1. Check the version consul --version

    D:\Develop\consul>consul --version
    Consul v1.13.1
    Revision c6d0f9ec
    Build Date 2022-08-11T19:07:00Z
    Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use    protocol >2 when speaking to compatible agents)
    D:\Develop\consul> 
    
  2. Use developer mode to start consul agent -dev
    D:\Develop\consul>consul agent -dev
    ==> Starting Consul agent...
               Version: '1.13.1'
            Build Date: '2022-08-11 19:07:00 +0000 UTC'
               Node ID: '51d45d1a-b90f-8fae-d6cc-b4a2244fdc49'
             Node name: 'LAPTOP-66KVCCQR'
            Datacenter: 'dc1' (Segment: '<all>')
                Server: true (Bootstrap: false)
           Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)
          Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
               Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false
    
    ==> Log data will now stream in as it occurs:
    
    2022-09-16T11:37:16.799+0800 [INFO]  agent.server.raft: initial configuration: index=1 servers="[{Suffrage:Voter ID:51d45d1a-b90f-8fae-d6cc-b4a2244fdc49 Address:127.0.0.1:8300}]"
    2022-09-16T11:37:16.799+0800 [INFO]  agent.server.raft: entering follower state: follower="Node at 127.0.0.1:8300 [Follower]" leader-address= leader-id=
    2022-09-16T11:37:16.802+0800 [INFO]  agent.server.serf.wan: serf: EventMemberJoin: LAPTOP-66KVCCQR.dc1 127.0.0.1
    2022-09-16T11:37:16.803+0800 [INFO]  agent.server.serf.lan: serf: EventMemberJoin: LAPTOP-66KVCCQR 127.0.0.1
    2022-09-16T11:37:16.803+0800 [INFO]  agent.router: Initializing LAN area manager
    .... 
    
  3. After startup, you can access Consul’s homepage by accessing the following address http://localhost:8500
    Insert image description here

Consul registration and discovery

Create Spring Boot project test-goods

Add the following dependencies to the pom.xml file

<!--SpringCloud consul-server -->
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!-- SpringBootIntegrateWebcomponents -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  </dependencies>
  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR10</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--If you can’t find it in the local warehouse, go to the official website to find it.-->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories> 

Properties configuration file adds the following configuration information

###consulService port number
server.port=8080
spring.application.name=test-goods
####consulRegistration center address
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name} 

Add @EnableDiscoveryClient annotation to project startup class

Write a controller test

 @RestController
@RequestMapping("/test")
public class Test {

    @GetMapping(value = "/test")
    public String test1() {
        return "I am test-goods Modulartestmethod";
    }
} 

Startup project

Check the management page of consul and find that test-goods has been registered.

Insert image description here

Access the interface to see if it can be accessed successfully

Insert image description here

At this point, the tutorial for registering a single project to Consul ends here.

Calling each other between Consul modules

This is similar to openFing in Spring Cloud, remote calling

Next we create a project and use this project to call the test method in the test-goods project.

Create test-user project

Add the following dependencies to the pom.xml file

<dependencies>
        <!--SpringCloud consul-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!-- SpringBootIntegrateWebcomponents -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
</dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR10</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--If you can’t find it in the local warehouse, go to the official website to find it.-->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories> 

Add the following information to the configuration file

###consulService port number
server.port=8081
spring.application.name=test-user
####consulRegistration center address
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name} 

Add the @EnableDiscoveryClient annotation to the startup class

Configuration bean/configuration class initializes objects for remote calls

@Configuration
public class ApplicationContextConfig
{
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
} 

Create a controller and call the test method of test-goods

@RestController
@RequestMapping("/user")
public class User {

    public static final String INVOKE_URL = "http://test-goods";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/test")
    public String paymentInfo() {
        String result = restTemplate.getForObject(INVOKE_URL + "/test/test", String.class);
        return result;
    }
} 

Start the project/implement remote calling

Insert image description here

Investigate the test method of test-user to see if the test-goods module can be accessed

At this point, the remote call of consul ends here.