From the previous article “Nacos Local Standalone Deployment Steps and Use,” you learned what Nacos is. Nacos provides the function of dynamic configuration service

What is the Nacos dynamic configuration service?

Here’s what the official said:

What is the Nacos Dynamic configuration service?

Dynamic configuration services manage application configuration and service configuration for all environments in a centralized, external, and dynamic manner.

Dynamic configuration eliminates the need to redeploy applications and services when configuration changes, making configuration management more efficient and agile.

Centralized configuration management makes it easier to implement stateless services and make it easier for services to scale flexibly on demand.

Nacos console functionality

Nacos provides an easy-to-use UI (console sample Demo) to manage the configuration of all services and applications. Nacos also provides a number of out-of-the-box configuration management features including configuration version tracking, Canary publishing, one-click rollback configuration, and client configuration update status tracking to more securely manage configuration changes and reduce the risk of configuration changes in a production environment.

Second, actual combat: Nacos service configuration center

The following is achieved through two large modules:

  • Create or modify configurations in Nacos
  • Load the Nacos configuration in the Spring Cloud application

2.1 Create a configuration in Nacos

Based on the previous article, the deployment runs Nacos and then opens the Configuration Management-Configuration List page. Address: http://localhost:8848/nacos/index.html#/configurationManagement

Click the create button in the upper right corner to enter the new configuration page, and the new configuration is as shown in the figure below:

Configuration details:

  • Data ID: is configured toconfig-service.yml. The Data ID is specified and is guaranteed to be globally unique.
  • Group: The default value isDEFAULT_GROUP, there is no need to modify.
  • Configuration format: Select the YAML configuration file format
  • Configure the content: Indicates the specific configuration. A simple key-value pair is configured here. In actual application scenarios, the configuration includes storage configuration, port configuration, and various middleware configurations

The standard format of Nacos Data ID is as follows:

${prefix}-${spring.profiles.active}.${file-extension}
Copy the code

Among them:

  • prefixDefault for:spring.application.nameThe value of the
  • spring.profiles.active: This case is empty. Generally, environment configuration such as dev test is specified
  • file-extension: Sets the content format

2.2 Creating a Spring Cloud Application

1. Create an application

Create a project named SpringCloud-nacos-config-sample

The project address is:

  • Github:github.com/JeffLi1993/…
  • Gitee:gitee.com/jeff1993/sp…

2. Configure POM dependencies

The pom.xml code is as follows:

<? 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>springcloud</groupId>
    <artifactId>springcloud-nacos-config-sample</artifactId>
    <version>0.01.-snapshot </version> <name> Springcloud-nacos-config-sample :: NacOS service configuration center case </name> <! --> <parent> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.32..RELEASE</version> </parent> <dependencies> <! - Nacos Config dependence - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-alibaba-nacos-config</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> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.1810.</version>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
                <version>0.22..RELEASE</version> </dependency> <! - Spring Cloud Hoxton. SR12 version depend on -- -- > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR7</version> <type>pom</type> <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
Copy the code

Which relies on:

  • Spring Cloud Alibaba Nacos Config dependency
  • The Spring Cloud Hoxton.SR12 version depends

3. Create a configuration file

In the Resources directory of the application project, create the application.yml file and fill it with the following information:

server:
  port: 8083Spring: application: name: config-serviceCopy the code

Among them:

  • server.portService port 8083 is specified
  • spring.application.nameThe service name is specifiedconfig-serviceTo create a new configuration with Nacos backgroundData IDThe values remain the same.

Why? Because see Nacos Config source org. Springframework. Cloud. Alibaba. Nacos. Client. NacosPropertySourceLocator# locate. The source code is as follows:

if (StringUtils.isEmpty(dataIdPrefix)) {
    dataIdPrefix = env.getProperty("spring.application.name");
}
Copy the code

If the Data ID is not configured, the spring.application.name service name configuration is read.

Go ahead and create the bootstrap.yml file and fill in the following information:

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.:8848# Nacos config center address file-extension: yML # config file formatCopy the code

Among them:

  • nacos.config.server-addrNacos address and port are specified
  • nacos.config.file-extensionThe configuration file format is yML

4. Create test classes and launch classes

Create a new Spring Cloud application startup class, ConfigApplication, with the following code:

/** * Spring Boot class ** Created by bysocket.com on 21/12/06. */
@SpringBootApplication  // Spring Boot application identifier
public class ProviderApplication {

    public static void main(String[] args) {
        // Program start entry
        // Start the embedded Tomcat and initialize the Spring environment and its Spring componentsSpringApplication.run(ProviderApplication.class,args); }}Copy the code

Create a new test control class ConfigController with the following code:

/** * Config example * 

* Created by bysocket.com on 21/12/07

@RestController @Slf4j @RefreshScope @Data public class ConfigController { @Value("${blog.name}") private String blogName; @GetMapping("/get") public String get(a) { return "ConfigController#get blog name = "+ getBlogName(); }}Copy the code

The code details are as follows:

  • @ValueAnnotation: @value annotates the Bean’s field or method parameters. It is responsible for setting default property values for the field or method parameters based on the expression. The usual format is an annotation + SpEL expression, such as @value (“SpEL expression “).
  • @RefreshScopeNote: Allows the Scope implementation of the Bean to be dynamically refreshed at run time. If the Bean is flushed, a new instance is created the next time the Bean is accessed and the method is executed. This indicates that when the application runs, the value of the Bean will be modified and take effect at the same time after the value of the corresponding configuration is modified in the Nacos console, achieving the effect of dynamic configuration.

5. Run tests

Start the above application and you will see the following information on the console:

2021-12- 0920:11:43.399  INFO 13909[-127.0. 01 _8848.] o.s.c.a.n.c.NacosPropertySourceBuilder   : Loading nacos data, dataId: 'config-service.yml', group: 'DEFAULT_GROUP'
2021-12- 0920:11:43.400  INFO 13909[-127.0. 01 _8848.] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-config-service.yml'}]
Copy the code

As you can see, Nacos configuration information dataId: ‘config-service.yml’ and group: ‘DEFAULT_GROUP’ have been loaded.

The address http://localhost:8083/get, open the browser response as shown:

Dynamic configuration test

Then go to the Nacos console, configuration list and click Modify config-service.yml configuration. Change www.bysocekt.com to bysocket.com and confirm publication. As shown in the figure:

You can see the following log from the console:

2021-12- 0920:31:30.747  INFO 13909[-127.0. 01 _8848.] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [blog.name]
Copy the code

To access the browser the address http://localhost:8083/get, response as shown:

The dynamic configuration is refreshed successfully.

Three, Nacos implementation of distributed configuration summary

This paper introduces in detail the Spring Cloud integration Nacos to achieve service distribution configuration. Two key points:

  • How do I set the corresponding configuration in Nacos
  • How can dependencies and annotations be associated with corresponding externalized configurations in the project

The resources

  • Official case: github.com/nacos-group…
  • IO/zh-CN /docs/…
  • Blog.didispace.com/spring-clou…

Code example address

In this article, you can check the springCloud-nacos-config-sample module of the open source project SpringCloud-learning-Example:

  • Github:github.com/JeffLi1993/…
  • Gitee:gitee.com/jeff1993/sp…

The following series of tutorials are recommended

  • Spring Cloud Tutorial series
  • Spring Boot 2.x Series tutorials
  • Elasticsearch Tutorial

Author: Mason (public name “programmer mason”) source: www.bysocket.com Welcome to reprint, also please keep this statement. Thank you very much!