1

In the previous article "Nacos Local Standalone Deployment Steps and Use" , you should know what Nacos is? Among them, Nacos provides dynamic configuration service function

1. What is the Nacos dynamic configuration service?

The official said:

Nacos dynamic configuration service?

The dynamic configuration service can manage the application configuration and service configuration of 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 makes it easier to expand services elastically on demand.

Nacos console features

Nacos provides a simple and easy-to-use UI (console sample Demo) to manage the configuration of all services and applications. Nacos also provides a series of out-of-the-box configuration management features, including configuration version tracking, canary release, one-click rollback configuration, and client configuration update status tracking, to more securely manage configuration changes and Reduce the risk of configuration changes.

2. Actual combat: Nacos realizes service configuration center

The following is achieved through two large modules:

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

2.1 Create a new configuration in Nacos

According to the previous article, deploy and run Nacos, and then open 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, the new configuration is shown in the figure:

Detailed configuration:

  • Data ID : The configuration is config-service.yml . Data ID is to specify the configuration and guarantee global uniqueness.
  • Group : The default configuration is DEFAULT_GROUP , no modification is required.
  • configuration format: select YAML configuration file format
  • Configuration content: Specific configuration content. Here is a simple configuration of a key-value pair. In fact, the actual application scenario will include storage configuration, port configuration, and various middleware configurations.

The Data ID is as follows:

${prefix}-${spring.profiles.active}.${file-extension}

in:

  • prefix : The default is the value spring.application.name
  • spring.profiles.active : This case is empty, generally specify the environment configuration such as dev test
  • file-extension : Configuration content format

2.2 Create Spring Cloud application

1. Create an application

New project, project name: springcloud-nacos-config-sample

The project address is at:

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.0.1-SNAPSHOT</version>
    <name>springcloud-nacos-config-sample :: Nacos 服务配置中心案例</name>

    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <dependencies>

        <!-- Nacos Config 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test 依赖 -->
        <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.18.10</version>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
                <version>0.2.2.RELEASE</version>
            </dependency>
            
            <!-- Spring Cloud Hoxton.SR12 版本依赖 -->
            <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>

Which relies on:

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

3. Create a configuration file

application.yml file in the resources directory of the application project and fill in the following information:

server:
  port: 8083 # 服务端口

spring:
  application:
    name: config-service # 服务名称

in:

  • server.port specifies service port 8083
  • spring.application.name specifies the service name config-service , which must be consistent with the value Data ID newly configured in the Nacos background.

why? Because look at the Nacos Config source code org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator#locate. The source code is as follows:

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

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

Continue to create the bootstrap.yml file and fill in the following information:

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848 # Nacos 配置中心地址
        file-extension: yml # 配置文件格式

in:

  • nacos.config.server-addr specifies the Nacos address and port
  • nacos.config.file-extension specifies the configuration file format as yml

4. Create a test class and a startup class

Create a new Spring Cloud application startup class ConfigApplication, the code is as follows:

/**
 * Spring Boot 服务启动类
 *
 * Created by bysocket.com on 21/12/06.
 */
@SpringBootApplication  // Spring Boot 应用标识
public class ProviderApplication {

    public static void main(String[] args) {
        // 程序启动入口
        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
        SpringApplication.run(ProviderApplication.class,args);
    }
}

Then create a new test control class ConfigController, the code is as follows:

/**
 * Config 案例
 * <p>
 * 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() {
        return "ConfigController#get blog name = " + getBlogName();
    }
}

The code is explained in detail as follows:

  • @Value Note: @Value annotates Bean fields or method parameters. The responsibility is to set default attribute values for fields or method parameters based on expressions. The usual format is annotation + SpEL expression, such as @Value("SpEL expression").
  • @RefreshScope Annotation: Allows to dynamically refresh Bean's Scope implementation at runtime. If the Bean is refreshed, a new instance will be created when the method is executed next time the Bean is accessed. This means that when the application is running, after the value of the corresponding configuration is modified in the Nacos console, the value of the Bean will be modified and validated at the same time to achieve the effect of dynamic configuration.

5. Run the test

Start the above application, you will see the following information in the console:

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

It can be seen here that the Nacos configuration information dataId: 'config-service.yml' and group: 'DEFAULT_GROUP' have been loaded.

Finally, open the address http://localhost:8083/get in the browser, and the response is as shown in the figure:

Dynamic configuration test

Then go to the Nacos console and click Modify config-service.yml configuration in the configuration list. www.bysocekt.com to bysocket.com , and then confirm the release. as the picture shows:

You can see the following log from the console:

2021-12-09 20:31:30.747  INFO 13909 --- [-127.0.0.1_8848] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [blog.name]

http://localhost:8083/get of the browser, and the response is as shown in the figure:

It indicates that the dynamic refresh configuration is successful.

Three, Nacos realizes distributed configuration summary

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

  • How to set the corresponding configuration in Nacos
  • How to associate the corresponding external configuration through dependencies and annotations in the project

Reference

Code sample address

For the case of this article, you can check the springcloud-nacos-config-sample module in the open source project springcloud-learning-example:

The following series of tutorials are recommended


子木聊出海
1.4k 声望3.1k 粉丝

公号:「子木聊出海」