Detailed introduction to the usage of Nacos configuration center

        The last article introduced the use of Nacos as a registration center . In addition, Nacos can also be used as a configuration center. Then this article will introduce the basic usage of Nacos as a configuration center. First, let's understand why we need to use the configuration center. .

1. Why do you need a configuration center:

Before there is no configuration center, the traditional application configuration has the following pain points:

(1) Using local static configuration, real-time performance cannot be guaranteed: Modifying the configuration is inflexible and requires a long test and release cycle, and cannot be notified to the client as soon as possible. Some configurations have high requirements for real-time performance, such as active-standby switching configuration. Or you need to modify the configuration in the event of a failure. In this case, the traditional static configuration or re-release method is used to configure the configuration, so the response speed is very slow, and the business risk is very large.

(2) It is easy to cause production accidents: For example, when publishing, it is easy to bring the configuration of the test environment to production, causing production accidents.

(3) The configuration is scattered and the format is not standard: some use the properties format, some use the xml format, and some store the DB. The team tends to build their own wheels, and there are various methods.

(4) The configuration lacks security auditing, version control, and configuration permission control functions: who? at what time? What configuration was modified? There is no way to trace back, and there is no way to roll back to the previous version in time if there is a problem; there is no way to authenticate and authorize the release of configuration changes, and everyone can modify and release the configuration.

        The configuration center is different from the traditional way of distributing configuration information to all corners of the system, and centrally and uniformly manages the configuration files in the system, instead of managing individual servers one by one. So what's the benefit of doing this?

(1) Through the configuration center, the configuration can be standardized and the format can be unified

(2) When the configuration information changes, the modification takes effect in real time, and the corresponding changes can be automatically sensed without restarting the server, and the new changes can be sent to the corresponding programs in a unified manner to quickly respond to changes. For example, a certain function is only for users in a certain region, and a certain function is only available during the big promotion period. After using the configuration center, only the relevant personnel need to dynamically adjust the parameters in the configuration center, basically in real time or quasi-real time. Adjust the corresponding business.

(3) The problem can also be traced through the audit function

Second, the use of Nacos configuration center:

        There are three main solutions for the configuration center in microservices: Nacos, Apollo, and Config+Bus. However, in this article, we mainly introduce the usage of Nacos as the configuration center. Readers interested in the other two methods can refer to the Internet by themselves.

1. Springboot integrates Nacos configuration center:

(1) First, we declare the version information of the project:

<properties>
    <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
    <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    <spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
</properties>

<!--  只声明依赖,不引入依赖 -->
<dependencyManagement>
    <dependencies>
        <!-- 声明springBoot版本 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- 声明springCloud版本 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- 声明 springCloud Alibaba 版本 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

(2) Add the maven dependency of the nacos configuration center:

<!-- SpringCloud Ailibaba Nacos Config -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

(3) Add the relevant configuration of the nacos configuration center in the application.properties file:

spring.profiles.active=dev
spring.application.name=cloud-producer-server
server.port=8080

# nacos 配置中心地址
spring.cloud.nacos.config.server-addr=localhost:8848
# 配置文件的类型
spring.cloud.nacos.config.file-extension=yaml

(4) Create a new configuration set with DataID cloud-producer-server-dev.yaml in the nacos console:

Why the DataID is named cloud-producer-server-dev.yaml will be described below

 (5) Write a test class:

//配置发布之后,动态刷新配置
@RefreshScope
@RestController
@RequestMapping("provider")
public class ProviderController
{
    // 使用原生注解@Value()导入配置
    @Value("${user.id}")
    private String id;
    @Value("${user.name}")
    private String name;
    @Value("${user.age}")
    private String age;

    @GetMapping("getNacosConfig")
    public String providerTest()
    {
        return "我是provider,已成功获取nacos配置中心的数据:(id:" + id + ",name:" + name + ",age:" + age +")";
    }
}

(6) Start service verification:

        Start the project, visit http://localhost:8080/provider/getNacosConfig interface, you can see that the configuration information of the nacos configuration center has taken effect and has been successfully obtained

(7) Verify the dynamic refresh configuration:

        The dynamic refresh of the configuration is one of the core functions of the configuration center. Suppose I need to modify the value of user.name now, will I directly change the configuration in Nacos to take effect? Let's try to directly modify the configuration in Nacos to "zhangsan", as shown below:

 Do not restart the project and revisit the interface at this time, the results are as follows:

        We found that the configuration has been dynamically refreshed, why is this? In fact, it is due to the effect of adding the @RefreshScope annotation to the class.

//配置发布之后,动态刷新配置
@RefreshScope
@RestController
@RequestMapping("provider")
public class ProviderController

2. The core concepts of Nacos:

2.1、Data ID:

(1) Naming format of Data ID:

        Earlier we demonstrated creating a new dataset with the DataID cloud-producer-server-dev.yaml in the nacos console, so what is this Data ID? Data ID is the unique identifier of a configuration set. An application can contain multiple configuration sets, and each configuration set needs to be identified by a meaningful name. So how does the Data ID get the value? The popular format is "prefix-environment-extension", as follows:

${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

① prefix: prefix, the default is the value of spring.application.name, or can be configured through the configuration item spring.cloud.nacos.config.prefix.

# 若不指定,默认采用应用名的方案
spring.application.name=cloud-producer-server

# 手动指定配置的dataID前缀标识
# spring.cloud.nacos.config.prefix=cloud-producer-server-config

② active: Configure the operating environment, which is the profile corresponding to the current environment.

Note: When spring.profiles.active is empty, the corresponding connector "-" will also not exist, and the splicing format of dataId becomes ${prefix}.${file-extension}

# dev表示开发环境
spring.profiles.active=dev

③ file-exetension: The type of the configuration file, the default is properties, it can also be configured through the configuration item spring.cloud.nacos.config.file-extension, currently supported types are TEXT, JSON, XML, YAML, HTML, Properties

# 指定配置文件类型为yaml文件
spring.cloud.nacos.config.file-extension=yaml

④ Final configuration:

        After the first three steps, we finally added a new configuration file to the console of the nacos configuration center: cloud-producer-server.yaml

2.2. Environment isolation - namespace Namespace:

        Nacos introduces the concept of namespace to manage and isolate multi-environment configurations and services. For example, you may have three different environments: the local development environment dev, the test environment test, and the production environment prod, then you can create three different Namespaces to distinguish different environments. Created as follows:

 After the creation is complete, you can see different namespaces on the configuration list of the Nacos console, as shown below:

        After successfully creating a new namespace, you can configure the id of the namespace in springboot's configuration file to switch to the corresponding namespace, and obtain the configuration file in the corresponding space, but if no namespace configuration is specified, the default configuration is Is in the public space, the way to specify the namespace is as follows:

# 对应创建的命名空间的ID,此处对应的是dev命名空间
cloud.nacos.config.namespace=483bb765-a42d-4112-90bc-50b8dff768b3

2.3. Business isolation-Group grouping:

        Group can also achieve the function of environment isolation, but the purpose of Group design is to group different services in the same environment, and divide the configuration files of different microservices into the same group. If Nacos does not specify Group, the default The grouping is DEFAULT_GROUP.

        If there is no group, imagine this scenario: there are two microservices, one is the order system and the other is the user system, but they have the same configuration, such as datasource-url, so how to distinguish? This is where Groups come in handy. In the above scenario, the order system and user system can be divided into a group, such as ORDER_GROUP, USER_GROUP, of course, this is a relatively fine-grained grouping, and multiple microservices can also be divided into a group according to the business of the enterprise.

        Next, let's demonstrate how to specify groups when creating a configuration set and when integrating. In the previous example, the new configuration set specifies the Group group in the following locations:

 Next group in the application.properties file:

spring.cloud.nacos.config.namespace=483bb765-a42d-4112-90bc-50b8dff768b3

3. Summary:

It is very simple for Nacos to implement configuration management and dynamic configuration refresh. The steps are summarized as follows:

  • ① Add the corresponding spring-cloud-starter-alibaba-nacos-config dependency
  • ② Import configuration using native annotation @Value()
  • ③ Use the native annotation @RefreshScope to refresh the configuration
  • ④ Do a good job of multi-environment configuration isolation (Namespace) and different business configuration isolation (Group) according to your own business scenarios

4. Shared configuration:

        When the number of our microservices increases, it is bound to have the same configuration. At this time, we can extract the same configuration as the common configuration in the project, such as the data source information in the cluster, the configuration information of the log, and nacos too. This way of writing multiple configuration sets in one configuration center is supported.

(1) We create two files with Data IDs db.yaml and log.yaml in nacos.

(2) Add some configuration contents to the configuration file respectively

(3) Add the following nacos configuration to the Springboot project:

spring:
  cloud:
    nacos:
      config:
        extension-configs[0]:
          data-id: db.yaml
          # 默认为DEFAULT_GROUP
          group: DEFAULT_GROUP
          # 是否动态刷新,默认为false
          refresh: true
        extension-configs[1]:
          data-id: log.yaml
          group: DEFAULT_GROUP
          refresh: true

In order to configure shared Data Ids between multiple applications more clearly, the official recommendation is to use shared-configs, the configuration is as follows:

spring:
  cloud:
    nacos:
      config:
        shared-configs[0]:
          data-id: db.yaml
          # 默认为DEFAULT_GROUP
          group: DEFAULT_GROUP   
          # 是否动态刷新,默认为false
          refresh: true   
        shared-configs[1]:
          data-id: log.yaml
          group: DEFAULT_GROUP
          refresh: true

(4) Thinking: How to select nacos when the same configuration appears in these two files?

        When multiple Data Ids have the same configuration at the same time, their priority relationship is spring.cloud.nacos.config.extension-configs[n].data-id where the larger the value of n, the higher the priority.

Note: The value of spring.cloud.nacos.config.extension-configs[n].data-id must have a file extension. The file extension can support both properties and yaml/yml. At this time, the configuration of spring.cloud.nacos.config.file-extension has no effect on the Data Id file extension of the custom extension configuration.

(5) Configure the loading priority in different ways:

        Nacos Configuration Center currently provides the following three configuration capabilities to pull related configurations from Nacos. When the three methods are used together, one of their priority relationships is: A < B < C:

  • A: Support multiple shared Data Id configurations through spring.cloud.nacos.config.shared-configs[n].data-id
  • B: Support the configuration of multiple extended Data Ids through spring.cloud.nacos.config.extension-configs[n].data-id
  • C: Automatically generate related Data Id configurations through internal related rules (spring.cloud.nacos.config.prefix, spring.cloud.nacos.config.file-extension, spring.cloud.nacos.config.group)

Reference article:

SpringBoot2.X integrates Nacos as configuration center

Fifty-five pictures tell you how strong is Nacos, the soul ferryman of microservices?

Guess you like

Origin blog.csdn.net/a745233700/article/details/122916208