We’ve looked at Spring Cloud Config previously:

  • Spring Cloud Series Config Center (1)
  • Spring Cloud Series Config Center (2)
  • Spring Cloud Series Config Center (3)

It provides the function of configuration center, but needs to work with Git, SVN, or external storage (such as various databases), and needs to work with Spring Cloud Bus “Spring Cloud Series Bus Message Bus” to achieve configuration refresh.

We also studied Spring Cloud Consul in the previous course, where we explained its use as a registry and as Spring Cloud’s official recommended alternative to the Eureka registry. Consul allows you to use the configuration center function provided by Consul, and you do not need git, SVN, or database cooperation, and you do not need Bus cooperation to refresh configurations.

Spring Cloud officially states that Consul can be used as an alternative to Spring Cloud Config configuration Center.

Official documents: https://cloud.spring.io/spring-cloud-static/spring-cloud-consul/2.2.2.RELEASE/reference/html/#spring-cloud-consul-config


We have already studied Consul registry, please refer to previous courses for those who have not. Today we’ll focus on how Consul can be used as a configuration hub.

Consul is introduced

Consul is an open source tool from HashiCorp for service discovery and configuration in distributed systems. Consul’s solution is more “one-stop” than other distributed service registration and discovery solutions, with built-in service registration and discovery framework, distributed consistency protocol implementation, health check, Key/Value storage (configuration center), and MULTI-data center solution that no longer relies on other tools (such as ZooKeeper, etc.). It’s also easier to use.

Consul is written in the Go language, making it naturally portable (Linux, Windows, and Mac OS support); The installation package contains only one executable file for easy deployment and works seamlessly with lightweight containers such as Docker.

Consul features

  • Raft algorithm

  • Service discovery

  • Health check

  • Key/Value storage (Configuration center)

  • Multi-data center

  • Supports HTTP and DNS interfaces

  • The official Web management interface is provided

Consul installation

Click the link to watch: Consul installation video (for more please follow the public account “Mr. Hello Ward”)

Consul is a third-party tool written in the GO language that needs to be installed separately.

download

Visit Consul’s website at https://www.consul.io to download the latest Consul version.


Supports multiple environments. The screenshot only shows some environments.


The installation

The Consul configuration center of a single node and a cluster has been described in detail in the previous tutorial. You can install Consul of a single node on Windows.

There is only one consul. Exe executable file in the downloaded package.


CD Go to the corresponding directory and run CMD to start Consul

-dev indicates that development mode runs Consul agent-dev-client =0.0.0.0Copy the code

To facilitate the startup, you can also create a script in the consul.exe directory with the following contents:

Consul agent - dev - client = 0.0.0.0pause
Copy the code

Visit admin back end: http://localhost:8500/ Seeing the following figure means that our Consul service has been successfully started.


Initial Configuration

Click the link to watch: initial configuration information video (for more information, please follow the public account “Mr. Hello Ward”)

Creating a base directory

Using Consul as the configuration center, the first step is to create a directory and store the configuration information in Consul.

Click the menu Key/Value and then click the Create button.


Create the Config/base directory, which can be interpreted as the outermost folder for the configuration file.


Creating an application Directory

Click Config to go to the folder.


Click the Create button again.


Create the orderService/ Application directory to store the default environment configuration information of the corresponding microservice application.


Multi-environment application directory

Assuming our project has multiple environments: default, test, dev, prod, create a multi-environment directory under the config directory.

  • orderServiceFolder correspondencedefaultThe environment
  • orderService-testFolder correspondencetestThe environment
  • orderService-devFolder correspondencedevThe environment
  • orderService-prodFolder correspondenceprodThe environment

Initial Configuration

Using the dev environment as an example, click orderService-dev to enter the folder.


Click the Create button to Create the Key/Value configuration information.


Fill in Key: orderServiceConfig

Fill in the Value:

name: order-service-dev
mysql:
  host: localhost
  port: 3006
 username: root
 password: root Copy the code

Assuming that the above information is the configuration information for the Order microservice, load the configuration information in Consul configuration center using a case.

Environment to prepare

Y-config-demo aggregation project. SpringBoot 2.2.4.RELEASE, Spring Cloud hoxton.sr1

  • order-service: Order service
  • order-service02: Order service

Practical cases

Check out the link to watch: Consul Configuration Center practice video

Add the dependent

For projects that need to obtain configuration information from Consul, add the spring-cloud-starter-consul-config dependency. Complete dependencies are as follows:

The order-service and order-service02 have the same dependency.


      

<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">
    <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>  <artifactId>order-service</artifactId>  <version>1.0 the SNAPSHOT</version>   <! -- Inheriting parent dependencies -->  <parent>  <groupId>com.example</groupId>  <artifactId>consul-config-demo</artifactId>  <version>1.0 the SNAPSHOT</version>  </parent>   <! -- Project dependencies -->  <dependencies>  <! Spring Boot Web dependency -->  <dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <! -- Spring boot actuator dependencies -->  <dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-actuator</artifactId>  </dependency>  <! -- Spring Cloud Consul Discovery -->  <dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-consul-discovery</artifactId>  </dependency>  <! -- Spring Cloud Consul config -->  <dependency>  <groupId>org.springframework.cloud</groupId>  <artifactId>spring-cloud-starter-consul-config</artifactId>  </dependency>   <! -- Spring Boot test dependency -->  <dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope>  <exclusions>  <exclusion>  <groupId>org.junit.vintage</groupId>  <artifactId>junit-vintage-engine</artifactId>  </exclusion>  </exclusions>  </dependency>  </dependencies>  </project> Copy the code

The configuration file

As usual, the configuration file must be called bootstrap.yml In addition to using Consul configuration center functionality, we are also registering microservices with Consul registry. The configuration items of order-service and order-service02 are the same except for the port number and the registered instance ID. The complete configurations are as follows:

server:
  port: 9090 # port

spring:
 application:
 name: order-service # app name  profiles:  active: dev The default environment is loaded by default  cloud:  consul:  # Consul server address  host: localhost  port: 8500  Configure the center configuration  config:  # Whether to enable configuration center. The default value is true  enabled: true  The default config folder is the outermost folder where the configuration file is located  prefix: config  The default value application is generally recommended to be set to the micro service application name  default-context: orderService  # config environment separator, default "," with the default-context configuration item  For example, orderService has environment default, dev, test, prod  Create orderService, orderService-dev, orderService-test, orderService-prod under config  profile-separator: The '-'  # set the configuration format to YAML  format: YAML  Key, Value in # Consul Key/Values correspond to the entire configuration file  data-key: orderServiceConfig  Load the config/orderService/ folder whose Key is orderServiceConfig Value  watch:  # Whether to enable automatic refresh. Default value: true  enabled: true  # Refresh frequency in milliseconds (default: 1000  delay: 1000  Configure service discovery  discovery:  register: true # Whether registration is required  instance-id: ${spring.application.name}-01 Register instance ID (must be unique)  service-name: ${spring.application.name} # service name  port: ${server.port} # service port  prefer-ip-address: true Whether to register with an IP address  ip-address: ${spring.cloud.client.ip-address} Service request IP Copy the code

Configuration file entity class

The order-service and Order-Service02 entity class codes are the same.

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component @ConfigurationProperties(prefix = "mysql") public class MySQLProperties {   private String host;  private Integer port;  private String username;  private String password;   public String getHost(a) {  return host;  }   public void setHost(String host) {  this.host = host;  }   public Integer getPort(a) {  return port;  }   public void setPort(Integer port) {  this.port = port;  }   public String getUsername(a) {  return username;  }   public void setUsername(String username) {  this.username = username;  }   public String getPassword(a) {  return password;  }   public void setPassword(String password) {  this.password = password;  }  } Copy the code

Control layer

The order-service and Order-Service02 control layer codes are the same.

Note that the @refreshScope annotation needs to be added to refresh the scope to automatically refresh the property values.

package com.example.controller;

import com.example.config.MySQLProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;  @RefreshScope @RestController public class ConfigController {   @Autowired  private MySQLProperties mySQLProperties;   @Value("${name}")  private String name;   @GetMapping("/name")  public String getName(a) {  return name;  }   @GetMapping("/mysql")  public MySQLProperties getMySQLProperties(a) {  return mySQLProperties;  }  } Copy the code

Start the class

The order-service and Order-Service02 startup classes have the same code.

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class OrderServiceApplication {   public static void main(String[] args) {  SpringApplication.run(OrderServiceApplication.class, args);  }  } Copy the code

test

Before modifying the configuration information

Visit: http://localhost:9090/name the results are as follows:


Visit: http://localhost:9090/mysql the results are as follows:


Modifying Configuration Information

Change the configuration information of the orderService-dev environment in Consul configuration center to:

name: The order - service - dev - 2.0
mysql:
  host: localhost
  port: 3006
 username: root123
 password: root123 Copy the code

After the configuration information is modified

The following information is displayed on the console:

[TaskScheduler-1] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-config/order-service-dev/'}, BootstrapPropertySource {name='bootstrapProperties-config/order-service/'}, BootstrapPropertySource {name='bootstrapProperties-config/orderService-dev/'}, BootstrapPropertySource {name='bootstrapProperties-config/orderService/'}]
[TaskScheduler-1] o.s.boot.SpringApplication               : The following profiles are active: dev
[TaskScheduler - 1] O.S.B oot. SpringApplication: Started application in 3.748 seconds (JVM running for 142.28)[TaskScheduler-1] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [name, mysql.password, mysql.username]
Copy the code

Consul uses the Spring scheduled task Spring TaskScheduler to listen for configuration file updates.

By default, it is a scheduled task thread pool, ThreadPoolTaskScheduler, whose poolSize is 1. To change TaskScheduler, please create a TaskScheduler use ConsulConfigAutoConfiguration. CONFIG_WATCH_TASK_SCHEDULER_NAME constant named bean type.


Visit: http://localhost:9090/name the results are as follows:


Visit: http://localhost:9090/mysql the results are as follows:


conclusion

HashiCorp’s Consul is a versatile package. Tools available to provide service discovery and service configuration. Developed with go language, it has good portability and is included in Spring Cloud.

On the registry side, Netflix Eureka stopped new version development and Consul emerged as a superior alternative.

In terms of configuration center, Consul can also be used as a configuration center instead of Spring Cloud Config, and cluster configuration updates can be implemented without Git, SVN, and Bus message Bus.


This article is licensed under a Creative Commons attribution – Noncommercial – No Deductive 4.0 International license.

You can see more articles about Spring Cloud in the category.

🤗 your likes and retweets are the biggest support for me.

📢 Scan code pay attention to Mr. Hallward “document + video” each article is equipped with a special video explanation, learning more easily oh ~