We have learned about Spring Cloud Config before:
- Consul configuration center of Spring Cloud series (I)
- Consul configuration center of Spring Cloud series (2)
- Consul configuration center of Spring Cloud series (3)
It provides the function of configuration center, but it needs to cooperate with git, svn or external storage (such as various databases), and Spring Cloud Bus Bus message bus of micro service series Implement configuration refresh. </a>
In the previous course, we also learned about Spring Cloud Consul. At that time, we explained its use scheme as a registration center, and it was officially recommended by Spring Cloud to replace Eureka registration center. Now that Consul is used, you can use the configuration center function provided by Consul, and do not need additional git, svn, database and other cooperation, and do not need to cooperate with Bus to achieve configuration refresh.
Spring Cloud officially states that Consul can be used as an alternative to the 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 learned about the Consul registration center. For those who have not learned, please refer to the previous courses "Consul Registration Center (I)" and "Consul Registration Center (II)" for learning. Today we're going to focus on how to use Consul as a configuration center.
Introduction to Consul
Consul is an open-source tool launched by HashiCorp to realize service discovery and configuration of distributed systems. Compared with other distributed service registration and discovery schemes, consul's scheme is more "one-stop". It has built-in service registration and discovery framework, distributed consistency protocol implementation, health check, Key/Value storage (configuration center) and multi data center scheme. It no longer needs to rely on other tools (such as ZooKeeper, etc.) and is easy to use.
Consul is written in Go language, so it has natural portability (supporting Linux, Windows and Mac OS); the installation package contains only one executable file, which is convenient for deployment, and can work seamlessly with lightweight containers such as Docker.
Consul characteristic
-
Raft algorithm
-
Service discovery
-
health examination
-
Key/Value storage (configuration center)
-
Multi data center
-
Support http and dns protocol interfaces
-
Official Web management interface
Consul installation
Click on the link to view: <a href= "https://video.zhihu.com/video/1245710836913651712" target= "_blank" >Consul install </a> video (for more, please pay attention to the official account "Hello Mr. Ward").
Consul is a third-party tool written in go language that needs to be installed and used separately.
download
Visit the website of Consul: https://www.consul.io Download the latest version of Consul.
It supports multiple environment installation, and only part of the environment is shown in the screenshot.
install
The installation method of single node and cluster has been explained in detail in the previous course. Here we mainly explain the role of Consul configuration center. We can install a single node Consul in Windows.
After downloading, there is only one execution file of consumer.exe in the package.
cd to the corresponding directory, use cmd to start Consul
# -dev indicates the development mode is running consul agent -dev -client=0.0.0.0
To facilitate startup, you can also create a script under the same level directory of consumer.exe to start it. The script content is as follows:
consul agent -dev -client=0.0.0.0 pause
Access management background: http://localhost:8500/ Seeing the figure below means that our Consul service has started successfully.
Initialize configuration
Click on the link to view: <a href= "https://video.zhihu.com/video/1245710910753935360" target= "_blank" > initialize configuration information </a> (for more, please pay attention to the official account, "Hello Mr. Ward").
Create 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 / basic directory, which can be understood as the outermost folder where the configuration file is located.
Create application directory
Click config to enter 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
Suppose our project has multiple environments: default, test, dev, prod. create a multi environment directory under the config directory.
- The orderService folder corresponds to the default environment
- The orderservice test folder corresponds to the test environment
- Orderservice dev folder corresponds to dev environment
- Orderservice prod folder corresponds to prod environment
Initialize configuration
Take the dev environment for 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 Value:
name: order-service-dev mysql: host: localhost port: 3006 username: root password: root
Assuming that the above content is the configuration information of the order microservice, let's load the configuration information in the Consul configuration center through a case.
Environmental preparation
Consumer config demo aggregation project. SpringBoot 2.2.4.RELEASE,Spring Cloud Hoxton.SR1.
- Order service: order service
- order-service02: order service
Practical cases
Click on the link to view: <a href= "https://video.zhihu.com/video/1245711008561664000" target= "_blank" >Consul configuration center practice video </a> (for more, please pay attention to the official account "Hello Mr. Ward").
Add dependency
The items that need to get configuration information from Consul mainly add spring cloud starter consumer config dependency. The complete dependency is as follows:
Order service and order-service02 depend on the same.
<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>order-service</artifactId> <version>1.0-SNAPSHOT</version> <!-- Inherit parent dependency --> <parent> <groupId>com.example</groupId> <artifactId>consul-config-demo</artifactId> <version>1.0-SNAPSHOT</version> </parent> <!-- Project dependency --> <dependencies> <!-- spring boot web rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- spring boot actuator rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- spring cloud consul discovery Service discovery dependency --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!-- spring cloud consul config Configuration center dependency --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency> <!-- spring boot test rely on --> <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>
configuration file
The old rule is that the configuration file must be bootstrap.yml. In addition to using the Consul configuration center function, we also register the microservice in the Consul registry. The configuration items of order-service and order-service02 are the same except for port and registered instance id. the complete configuration is as follows:
server: port: 9090 # port spring: application: name: order-service # apply name profiles: active: dev # Specify the environment and load the default environment by default cloud: consul: # Consul server address host: localhost port: 8500 # Configuration center related configuration config: # Enable configuration center, default value is true enabled: true # Set the basic folder of the configuration. The default value of config can be understood as the outermost folder of the configuration file prefix: config # Set the folder name of the application. The default value of application is generally recommended to be set as the microservice application name default-context: orderService # Configure environment separator, match default "," with default context configuration item # For example, the application orderService has environment default, dev, test and prod respectively # Just create the orderService, orderService dev, orderService test and orderService prod folders under the config folder profile-separator: '-' # Specify the configuration format as yaml format: YAML # The Key in Key/Values of Consul corresponds to the entire configuration file data-key: orderServiceConfig # The above configuration can be understood as: load the configuration information corresponding to the Value whose Key is orderServiceConfig under the config/orderService / folder watch: # Whether to enable automatic refresh? The default value is true enabled: true # Refresh rate in milliseconds, default 1000 delay: 1000 # Service discovery related configuration discovery: register: true # Need to register instance-id: ${spring.application.name}-01 # Registration instance id (must be unique) service-name: ${spring.application.name} # Service name port: ${server.port} # Service port prefer-ip-address: true # Use ip address to register ip-address: ${spring.cloud.client.ip-address} # Service request ip
Profile 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() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
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() { return name; } @GetMapping("/mysql") public MySQLProperties getMySQLProperties() { return mySQLProperties; } }
Startup class
The order-service and order-service02 startup class codes are the same.
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); } }
test
Before modifying configuration information
Visit: http://localhost:9090/name The results are as follows:
Visit: http://localhost:9090/mysql The results are as follows:
Modify configuration information
Modify the configuration information of the Consul configuration center orderservice dev environment to:
name: order-service-dev-2.0 mysql: host: localhost port: 3006 username: root123 password: root123
After modifying the configuration information
The console print information is as follows:
[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.boot.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]
Consul uses the Spring task scheduler to listen for updates to the configuration file.
By default, it is a timed task thread pool ThreadPoolTaskScheduler with a poolSize value of 1. To change the TaskScheduler, create a bean type named by the TaskScheduler using the consulconfiguautoconfiguration.config > wait > task > schedule > name constant.
Visit: http://localhost:9090/name The results are as follows:
Visit: http://localhost:9090/mysql The results are as follows:
summary
Consul of HashiCorp is a versatile component. Tools that can be used to provide service discovery and service configuration. Developed in go language, it has good portability and is included by Spring Cloud.
On the registry side, Netflix Eureka stopped developing new versions, and Consul became an excellent alternative.
In terms of configuration center, Consul can also replace Spring Cloud Config as the configuration center, and can realize cluster configuration update without using Git, SVN and Bus message Bus.
This paper adopts Intellectual sharing "signature - non-commercial use - no deduction 4.0 international" License Agreement.
You can go through classification See more about Spring Cloud The article.
Your comments and forwarding are the biggest support for me.
📢 Scan the code and follow Mr. halloward's "document + video". Each article is provided with a special video explanation, which makes learning easier~