Spring cloud configuration center

Foreword: if you want to put the project into the server and run, you can use the configuration center SpringCloud Config here;

1, SpringCloud Config

Microservices It means that the business in a single application should be divided into one sub service. The granularity of each service is relatively small, so there will be a large number of services in the system. Because each service needs the necessary configuration information to run, a centralized and dynamic configuration management facility is essential. Spring Cloud provides ConfigServer to solve this problem Spring Cloud Config provides centralized external configuration support for microservices in the microservice architecture, and the configuration server provides a centralized external configuration for all environments of different microservice applications. The cloud server and the spring config server are divided into two parts.

Relation diagram

The server is also known as the distributed configuration center. It is an independent micro service application, which is used to connect to the configuration server and provide the client with access interfaces such as obtaining configuration information and encrypting / decrypting information. The client manages application resources and business-related configuration contents through the established configuration center, and obtains and loads configuration information from the configuration center at startup. The configuration server uses git to store configuration information by default, which is helpful for version management of environment configuration, and can easily manage and access configuration contents through git client tools

 

An application system using microservice architecture may include hundreds of microservices with the same configuration and different requirements:

Different environments have different configurations: for example, data sources are different in different environments (development, testing, production), which can be configured through the configuration center

It can be adjusted dynamically during operation. For example, dynamically adjust the size of the data source connection pool or fuse threshold according to the load status of each microservice, and do not stop the microservice during adjustment (the configuration can be updated automatically after modification)

2, Package the project

1. First export the dto dependent project imported in the parent project

 

2. Export parent project first

Note out the identification in pom file:

Guide Package:

 

3. Guide the subclass producers to the package

Take out the jar package

4. It can be run in cmd

 

III. solution

1. Problem: multiple projects depend on some configurations. If a configuration changes, you have to change the source code of the project

2. Solution: use the configuration center (SpringCloud config)

nacos config

contrast:

3. Demonstration

① Import dependency in parent project

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

Release the recognizer:

② . create a new client project

 

 

pom file:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lj</groupId>
    <artifactId>config-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>config-client</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <artifactId>SpringCloud</artifactId>
        <groupId>org.lj</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <mainClass>com.lj.configclient.ConfigClientApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

③. New configuration

Note: application in nacos service In the properties file, you need to pay attention to the password to connect to the database

email:

        host: qq.com

        username: root

        password: 123456

 

④ Read the content of the configuration center from the project

Create a new application YML and bootstrap YML file

By default, SpringBoot supports configuration files in two formats: properties and YAML.
bootstrap.yml (bootstrap.properties) is used to execute during program boot, and is used to read earlier configuration information. For example, it can be used to configure application Parameters used in YML
application.yml (application.properties) application specific configuration information, which can be used to configure public parameters to be used in subsequent modules.
bootstrap.yml precedes application YML loading

Import dependency in parent class:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

bootstrap.yml file:

server:
  #Project port number (after being configured in bootstrap.yml, it can not be configured in application.yml)
  port: 8083

#spring:
#  application:
#    # The application name corresponds to the Data Id of the nacos configuration center
#    name: nacos-config-client
#  cloud:
#    nacos:
#      #Specify the address of the nacos Registry (after being configured in bootstrap.yml, it can not be configured in application.yml)
#      discovery:
#        server-addr: 127.0.0.1:8848
#      config:
#        #If it is not filled in, the default is the application name of the project
#        prefix: ${spring.application.name}
#        #Specify the nacos configuration center address
#        server-addr: 127.0.0.1:8848
#        #Specify profile suffix
#        file-extension: yml
#        #Note that the namespace configuration does not use the name, but the ID of the namespace.
#        #namespace: 3a74eaaa-031c-4cae-9441-3c159febeb79
#        #The data IDs of other configuration files to be imported are separated by commas
#        shared-dataids: redis-config.yml
#        refreshable-dataids: redis-config.yml

spring:
  application:
    # The configuration file corresponding to data ID will be automatically pulled according to the service name If the data ID is inconsistent with the service name, you need to specify the data ID manually
    # The configuration file with the same data ID as the service name is called the default configuration file
    # In addition to the default configuration file, other configuration files must be suffixed
    name: config-client
  cloud:
    nacos:
      discovery:  #Registration Center
        server-addr: 127.0.0.1:8848
        # username: nacos
        # password: nacos
      config:  #Configuration center
        prefix: ${spring.application.name}
        #Specify the nacos configuration center address
        server-addr: 127.0.0.1:8848
        file-extension: yml # The file extension name of the dataId of the used Nacos configuration set is also the configuration format of the Nacos configuration set. The default is properties
#        namespace: e96d14f0-6f80-4e2c-9f0b-5467da74bd32  # The namespace of the used nacos, which is null by default
        group: DEFAULT_GROUP # The Nacos configuration group used is DEFAULT_GROUP
        # Shared configuration set array
        shared-configs:
          - data-id: config-redis.yml
            group: DEFAULT_GROUP # The Nacos configuration group used is DEFAULT_GROUP
            refresh: true # Whether to automatically refresh the configuration. The default is false

Start class injection here:

@SpringBootApplication
@EnableDiscoveryClient
package com.lj.configclient;

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

/**
 * @author My
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigClientApplication {

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

}

In configuration class

package com.lj.configclient;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "email")
@Data
public class EmailProperties {

    private String host;
    private String username;
    private String password;


}

 

Create a new test class and get the data:

Take the configuration center directly to the application YML file

package com.lj.configclient;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author My
 */
@RestController
@SuppressWarnings("all")  //Shielding warning
@RefreshScope   //Refresh configuration
public class TestController {

    @Value("${email.host}")
    private String host;
    @Value("${email.username}")
    private String username;
    @Value("${email.password}")
    private String password;

    @Value("${redis.host}")
    private String redisHost;
    @Value("${redis.port}")
    private String redisPort;

    @Autowired
    private EmailProperties properties;

    @RequestMapping("/test01")
    public String test01(){
        StringBuffer sb = new StringBuffer();
        sb.append("<b>host</b>"+host);
        sb.append("<br><b>username</b>"+username);
        sb.append("<br><b>password</b>"+password);
        sb.append("<br><b>properties</b>"+properties);
        sb.append("<br><b>port</b>"+redisPort);
        sb.append("<br><b>host</b>"+redisHost);
        return sb.toString();
    }
}

result:

⑤. Remote configuration reading

I. new configuration center

II. Shared configuration set array

bootstrap.yml:

#Shared configuration set array
        shared-configs:
            - data-id: config-redis.yml
              group: DEFAULT_GROUP # uses the Nacos configuration group, which defaults to DEFAULT_GROUP
refresh: true # whether to automatically refresh the configuration. The default is false@RefreshScope Realize real-time update of configuration

server:
  #Project port number (after being configured in bootstrap.yml, it can not be configured in application.yml)
  port: 8083

#spring:
#  application:
#    # The application name corresponds to the Data Id of the nacos configuration center
#    name: nacos-config-client
#  cloud:
#    nacos:
#      #Specify the address of the nacos Registry (after being configured in bootstrap.yml, it can not be configured in application.yml)
#      discovery:
#        server-addr: 127.0.0.1:8848
#      config:
#        #If it is not filled in, the default is the application name of the project
#        prefix: ${spring.application.name}
#        #Specify the nacos configuration center address
#        server-addr: 127.0.0.1:8848
#        #Specify profile suffix
#        file-extension: yml
#        #Note that the namespace configuration does not use the name, but the ID of the namespace.
#        #namespace: 3a74eaaa-031c-4cae-9441-3c159febeb79
#        #The data IDs of other configuration files to be imported are separated by commas
#        shared-dataids: redis-config.yml
#        refreshable-dataids: redis-config.yml

spring:
  application:
    # The configuration file corresponding to data ID will be automatically pulled according to the service name If the data ID is inconsistent with the service name, you need to specify the data ID manually
    # The configuration file with the same data ID as the service name is called the default configuration file
    # In addition to the default configuration file, other configuration files must be suffixed
    name: config-client
  cloud:
    nacos:
      discovery:  #Registration Center
        server-addr: 127.0.0.1:8848
        # username: nacos
        # password: nacos
      config:  #Configuration center
        prefix: ${spring.application.name}
        #Specify the nacos configuration center address
        server-addr: 127.0.0.1:8848
        file-extension: yml # The file extension name of the dataId of the used Nacos configuration set is also the configuration format of the Nacos configuration set. The default is properties
#        namespace: e96d14f0-6f80-4e2c-9f0b-5467da74bd32  # The namespace of the used nacos, which is null by default
        group: DEFAULT_GROUP # The Nacos configuration group used is DEFAULT_GROUP
        # Shared configuration set array
        shared-configs:
          - data-id: config-redis.yml
            group: DEFAULT_GROUP # The Nacos configuration group used is DEFAULT_GROUP
            refresh: true # Whether to automatically refresh the configuration. The default is false

III. test type TestController

@Value("${redis.host}")
private String redisHost;
@Value("${redis.port}")
private String redisPort;
@RequestMapping("/test01")
public String test01(){
    StringBuffer sb = new StringBuffer();
    sb.append("<b>host</b>"+host);
    sb.append("<br><b>username</b>"+username);
    sb.append("<br><b>password</b>"+password);
    sb.append("<br><b>properties</b>"+properties);
    sb.append("<br><b>port</b>"+redisPort);
    sb.append("<br><b>host</b>"+redisHost);
    return sb.toString();
}

⑥. Cutting environment

Namespace found:

Create several spaces:

 

 

 

Note: you need to change the cloned file into yml file in the space

 

The namespace id should be filled in the yml file for which space is needed

 

Operation behavior development environment:

 

⑦. Shared location + Environment

Export config client project:

Take out the jar package:

 

Run the jar package:

 

Unassign the namespace of this yml file. It may die

Run directly to the file and execute the following statement,

java -jar xx.jar --spring.cloud.nacos.config.namespace = namespace id

Successful startup:

 

Note: the configuration content in the nacos configuration center cannot appear in Chinese, otherwise an error will be reported

End of current period~~~~

 

Keywords: Java Spring Cloud Microservices

Added by croix on Mon, 21 Feb 2022 11:18:03 +0200