Registration Center Consul

Microservices have become the mainstream technology architecture pursued by major manufacturers, and the prospect of learning microservices is very promising, and SpringCloud has become the mainstream microservice technology stack. This series of articles will focus on the SpringCloud technology stack, and comprehensively analyze and explain the actual application of the SpringCloud technology stack in the microservice scenario.

Registration Center

Knowledge Index

  • What is a registry
  • cap theorem
  • Registry comparison
  • service registration
  • service call

1 What is a registry

When microservices call each other, they need to know the specific address of the called service and whether it is healthy (whether the server responds), which requires the registry to have these two capabilities: 1. The ability to allow service registration, 2. The ability to monitor services . If there is only one registry, our system cannot run normally when it cannot provide services for various reasons. Therefore, the registry is required to have the ability to cluster, and the data between clusters must be consistent. During failover of the host, the data of the master and slave nodes may be inconsistent, which may result in the incorrect service list being obtained when the service is called. Therefore, it must also have high availability and consistent cluster capabilities.

2 Spring Cloud supported registries and comparisons

2.1 cap theorem

CAP原则Also known as CAP定理, refers to in a distributed system, consistency ( Consistency), availability ( Availability), partition fault tolerance ( Partition tolerance). CAP 原则It means that these three elements can only achieve two points at most at the same time, and it is impossible to take care of all three.

Consistency 一致性: Whether all data backups have the same value at the same time. (equivalent to all nodes accessing the same latest copy of data)

Availability 可用性: Whether the cluster as a whole can still respond to the client's read and write requests after some nodes in the cluster fail. (High availability for data updates)

Partition Tolerance 容错性: In terms of practical effect, the partition is equivalent to the time limit for communication. If the system cannot achieve data consistency within the time limit, it means that a partition has occurred, and a choice must be made between C and A for the current operation.

CAP原则The essence of it is either AP, either CP, or AC, but it doesn't exist CAP. If there is no copy of data in a distributed system, then the system must meet the strong consistency condition, because there is only one data, and there will be no data inconsistency. At this time, the two elements of C and P are available, but if the network occurs in the system Partition status or downtime will inevitably lead to some data inaccessibility, and the availability condition cannot be satisfied at this time, that is, the system is obtained in this case CP, but CAPcannot be satisfied at the same time.

2.2 Comparison of registration centers

nacos Eureka Consul Zookeeper
Conformance Protocol CP+AP AP CP CP
health examination TCP/HTTP/MYSQL/Client Beat Client Beat TCP/HTTP/gRPC/Cmd Keep Alive
load balancing strategy weight/metadata/Selector Ribbon Fabio
Avalanche protection Have Have none none
Automatically log out of the instance support support not support support
access agreement HTTP/DNS HTTP HTTP/DNS TCP
Monitoring support support support support support
Multiple data centers support support support not support
Sync across registries support not support support not support
SpringCloud integration support support support support
Dubbo integration support not support not support support
K8S integration support not support support not support

The Eureka2.x version has been announced as closed source, which will be introduced Nacosin the subsequent Spring CloudAlibabachapters. In this article, we mainly Consuldemonstrate the configuration and use of the registry.

3 Consul

3.1 Introduction to Consul

ConsulIt is HashiCorpan open source tool launched by the company to realize service discovery and configuration of distributed systems. Compared with other distributed service registration and discovery solutions, Consulthe solution is more "one-stop", with built-in service registration and discovery framework, distributed consistency protocol implementation, health check, Key/Valuestorage, multi-data center solutions, and no longer need to rely on other tools (eg ZooKeeper, etc. ). It is also simpler to use. WrittenConsul in , so it is naturally portable (supports , and ); the installation package contains only one executable file, which is convenient for deployment and works seamlessly with lightweight containers such as .Go 语言LinuxwindowsMac OS XDocker

3.2 Consul installation (virtual machine simulates linux operation)

View all dockermirrors

docker images

image-20220313163055030

pull Consulimage

docker pull consul # 默认拉取latest

image-20220313163509121

ConsulYou can check again that the mirror already exists

image-20220313163723377

start a Consulcontainer

docker run -d -p 8500:8500 --restart=always --name=consul consul:latest agent -server -bootstrap -ui -node=1 -client='0.0.0.0'

image-20220313163630168

View launched containers

image-20220313163841248

Browser access to the 8500port of the installation machine

http://ip:8500

Jump to the following page to indicate that the installation is successful

image-20220313163954348

4 Service Registration

Next we develop a simple service to register with the registry.

4.1 Create a maven project

Create a new spring_cloud_demosproject and create a service_providermodule, the directory structure is as follows

image-20220313164838582

4.2 Introducing dependencies

Imported in parent projectspring-boot-starter-parent

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.7.RELEASE</version>
</parent>

It ends up as follows:

image-20220313171722960

ConsulIntroduce dependencies in service_provider

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <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-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR5</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

It ends up as follows:

image-20220313171739413

4.3 Configuration files

server:
  port: 8001 #服务端口
spring:
  application:
    name: service-provider #服务名
  cloud:
    consul:
      host: 192.168.184.128 #注册中心地址
      port: 8500 #注册中心端口
      discovery:
        service-name: ${
    
    spring.application.name} #注册中心中该服务的服务名

4.4 Writing code

4.4.1 Startup class

/**
 * Copyright (c) 2022 itmentu.com, All rights reserved.
 *
 * @Author: yang
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProvicerApplication {
    
    

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

Code description:

1:@EnableDiscoveryClient表示发现注册中心,向注册中心注册服务
2:@SpringBootApplication见springboot章节

4.4.2 Interface Writing

/**
 * Copyright (c) 2022 itmentu.com, All rights reserved.
 *
 * @Author: yang
 */
@RestController
public class HelloController {
    
    

    @GetMapping("/hello")
    public String hello(){
    
    
        return "hello!";
    }
}

4.4.3 Running the startup class

After running, the console sees the following content, indicating that the startup is successful:

image-20220313174302721

Also check the registration center page that the service has been successfully registered

image-20220313174337673

5 Service calls

5.1 Create submodule service_consumer

image-20220313174441071

5.2 Introducing dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <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-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR5</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

5.3 Configuration files

server:
  port: 8001 #服务端口
spring:
  application:
    name: service-provider #服务名
  cloud:
    consul:
      host: 192.168.184.128 #注册中心地址
      port: 8500 #注册中心端口
      discovery:
        service-name: ${
    
    spring.application.name} #注册中心中该服务的服务名
        register: false #不注册到注册中心

illustrate:

1:由于消费者不需要注册到注册中心,所以spring.cloud.consul.discovery.register为false

5.4 Writing code

5.4.1 Startup class

/**
 * Copyright (c) 2022 itmentu.com, All rights reserved.
 *
 * @Author: yang
 */
@SpringBootApplication
public class ServiceConsumerApplication {
    
    

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

    @Bean
    public RestTemplate restTemplate(){
    
    
        return new RestTemplate();
    }
}

Code Description:

1:注册一个RestTemplate到spring容器中以便使用

5.4.2 Interface Writing

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    
    
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/hello")
    public String hello(){
    
    
        //1、获取注册中心中注册的service-provider实例列表
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service-provider");
        //2、获取实例
        ServiceInstance serviceInstance = serviceInstanceList.get(0);
        //3、根据实例的信息拼接的请求地址
        String url = serviceInstance.getUri()+ "/hello";
        //4、发送请求
        return restTemplate.getForObject(url,String.class);
    }
}

Code Description:

1:DiscoveryClient用于获取注册中心中对应服务的实例
2:serviceInstance.getUri()表示实例中的地址包括ip端口
3:RestTemplate用于进行rest方式的http请求

5.4.3 Running the startup class and accessing the interface

browser access

http://localhost:8002/consumer/hello

can be seen

image-20220313175240280

stance.getUri()+ "/hello";
//4, send request
return restTemplate.getForObject(url,String.class);
}
}


代码说明:

```properties
1:DiscoveryClient用于获取注册中心中对应服务的实例
2:serviceInstance.getUri()表示实例中的地址包括ip端口
3:RestTemplate用于进行rest方式的http请求

5.4.3 Running the startup class and accessing the interface

browser access

http://localhost:8002/consumer/hello

can be seen

[External link image dumping...(img-SEv3pOhQ-1647865478979)]

Indicates that we have successfully consumeraccessed and responded to service_providerthe data/hello接口

Guess you like

Origin blog.csdn.net/scmagic/article/details/123645129