Spring Cloud (5): Consul service registration and discovery

1. Introduction to Consul

Consul is an open source distributed service discovery and configuration management system developed by HashiCorp using the Go language.
Provides the service management, configuration center, control bus and other functions in the microservice system. Each of these functions can be used separately or together to build a full service network. In short, Consul provides a complete service Grid solution.

Has many advantages: including: based on the raft protocol, relatively simple. Support health check, support HTTP and DNS protocols at the same time, support cross-data center WAN cluster, provide graphical interface, cross-platform, support windows, linux, mac.

  • Service discovery: provide two discovery methods: HTTP and DNS
  • Health monitoring: support multiple protocols, HTTP, TCP, Docker, Shell script customization
  • KV storage: key and value storage methods
  • Multiple data centers: Consul supports multiple data centers
  • Visual web interface

2. Consul installation

Tutorial: https://www.springcloud.cc/spring-cloud-consul.html

2.1 docker version

Download address: https://www.consul.io/downloads.html is
too slow, you can use docker to install

docker pull consul:1.6.1
docker run --name consul -p 8500:8500  -d consul:1.6.1

Access: ip of the host where consul is located: 8500
Insert picture description here

2.2 Windows version

  • After the download is complete, there is only one consul.exe file, double-click to run it under the hard disk path to view the version information
consul --version
  • Start with development mode
consul agent -dev

Visit: http;//localhost:8500

3 Service provider

3.1 Build module

Create a new cloud-providerconsul-payment8006 module

3.2 Change POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-demo</artifactId>
        <groupId>com.lele.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-providerconsul-payment8006</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

3.3 建l

server:
  port: 8006

spring:
  application:
    name: consul-provider-payment

# consul注册中心地址
  cloud:
    consul:
      host: localhost #consul所在服务器的ip
      port: 8500
      discovery:
        #hostname: 127.0.0.1
        service-name: ${
    
    spring.application.name}
        heartbeat:
          enabled: true

3.4 Main Startup Class

package com.lele.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author: lele
 * @date: 2021/3/12 7:17
 * @description:
 */
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8006 {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(PaymentMain8006.class, args);
    }
}

3.5 controller

package com.lele.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author: lele
 * @date: 2021/3/12 7:19
 * @description:
 */
@RestController
@Slf4j
public class PaymentController {
    
    

    @Value("${server.port}")
    private String serverPort;

    @RequestMapping(value = "/payment/consul")
    public String paymentConsul() {
    
    
        return "spring cloud with consul:" + serverPort + "\t" + UUID.randomUUID().toString();
    }
}

3.6 Testing

Start 8006, visit http://localhost:8006/payment/consul
Insert picture description here

4. Service Consumer

4.1 Build module

Create a new cloud-consumerconsul-order80 module

4.2 POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-demo</artifactId>
        <groupId>com.lele.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumerconsul-order80</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

4.3 marl

server:
  port: 80

spring:
  application:
    name: cloud-consumer-order
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${
    
    spring.application.name}
        heartbeat:
          enabled: true

4.4 Main Startup Class

package com.lele.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author: lele
 * @date: 2021/3/13 18:49
 * @description:
 */
@SpringBootApplication
@EnableDiscoveryClient  //该注解用于向使用consul或者zookeeper作为注册中心时注册服务
public class OrderConsulMain80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderConsulMain80.class, args);
    }
}
  • ApplicationContextConfig
package com.lele.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author: lele
 * @date: 2021/3/13 18:56
 * @description:
 */
@Configuration
public class ApplicationContextConfig {
    
    
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
    
    
        return new RestTemplate();
    }
}

4.5 controller

package com.lele.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author: lele
 * @date: 2021/3/13 19:00
 * @description:
 */
@RestController
@Slf4j
public class OrderConsulController {
    
    
    public static final String INVOKE_URL = "http://consul-provider-payment";

    @Resource
    private RestTemplate restTemplate;

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

4.6 Testing

Start 8006 and visit http://localhost:8006/payment/consul;
Insert picture description here

Restart Consul80 and visit http://localhost/consumer/payment/consul
Insert picture description here

5. Similarities and differences between the three registration centers

CAP

  • C: Consistency (strong consistency)
  • A: Availability
  • P: Partition tolerance (Partition tolerance)
    CAP theory focuses on the granularity of the data, rather than the overall system design strategy.

Classic CAP diagram

  • At most, only two can be better satisfied at the same time;
  • The core of the CAP theory is: a distributed system cannot satisfy the three requirements of consistency, availability and partition fault tolerance at the same time. Therefore, according to the CAP principle, the NoSQL database is divided into satisfying the CA principle, satisfying the CP principle and satisfying the AP. Three categories of principles:
    • CA-single point cluster, a system that meets consistency and availability, usually not very powerful in scalability
    • CP-satisfy consistency, partition fault tolerance system, usually performance is not particularly high
    • AP-a system that meets availability and partition fault tolerance may generally have lower requirements for consistency.
      Insert picture description here

AP (Eureka)
AP architecture, when network partitions appear, in order to ensure availability, system B can return the old value to ensure system availability.
Conclusion: Violated the requirements of consistency C, and only met the availability and partition fault tolerance, namely AP.
Insert picture description here

CP (Zookeeper/Consul)
CP architecture, when the network partition appears, in order to ensure consistency, the request must be rejected, otherwise the consistency cannot be guaranteed.
Conclusion: Violation of the requirements of availability A, only meets the consistency and partition fault tolerance, namely CP .
Insert picture description here

Guess you like

Origin blog.csdn.net/houwanle/article/details/114681143