Source code address: gitee.com/fighter3/es…

Continuously updated…

When we introduced Nacos earlier, we said that Nacos can be used as a configuration center as well as a registry, which is done by SpringCloud Config under the SpringCloud Netfilx architecture.

Why do you need to configure the center? You think about it, under the micro service development system, the system can be split into several dozens, hundreds of service, at the time of production, each service may be deployed dozens of hundreds of nodes, and is usually and multiple environments, such as development, test, pre-release, to produce and so on, without a centralized allocation center, one by one to manage, that’s what a 😥.

Now let’s have fun learning about Nacos as a distributed configuration center!

1. Basic concepts of Nacos configuration

Before we get started, let’s take a look at some basic concepts of Nacos configuration.

In the figure above, we can see the main concepts of Nacos as a configuration hub:

  • The namespace

Distinguish between environments, such as dev, test, prod, and so on.

Used for configuration isolation of tenant granularity. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.

  • Configure grouping

Multiple configuration files are grouped together to form groups, which are generally used to distinguish projects. For example, a school uses TEACHER_GROUP for teachers and STUDENT_GROUP for students.

A set of configuration sets in Nacos, one of the dimensions of organizational configuration. Configuration sets are grouped by a meaningful string, such as Buy or Trade, to distinguish between configuration sets with the same Data ID. When you create a configuration on Nacos, DEFAULT_GROUP is used by default if the name of the configuration group is not specified. A common scenario for configuring groups: different applications or components use the same configuration type, such as database_URL configuration and MQ_topic configuration.

  • Configuration set

Multiple key-value pairs, typically a configuration file.

A set of related or unrelated configuration items is called a configuration set (multiple key-value pairs/one profile). In a system, a configuration file is usually a configuration set that contains all aspects of the system configuration. For example, a configuration set may contain configuration items such as data sources, thread pools, logging levels, and so on.

  • Configuration set ID

Give the configuration file a globally unique ID.

The ID of a configuration set in Nacos. The configuration set ID is one of the dimensions in which the configuration is organized. The Data ID is typically used to organize the configuration set that divides the system. A system or application can contain multiple configuration sets, each of which can be identified by a meaningful name. Data ID usually use class Java packages (such as com. Taobao. Tc. Refund. The level) the naming rules to ensure the global uniqueness. This naming rule is optional.

  • Configuration items

A key-value pair <Key = Value>

A specific configurable parameter and its range (a key-value pair), usually in the form param-key=param-value. For example, we used to configure the system log output level (logLevel = INFO | WARN | ERROR) is a configuration item.

I’ll show you an example of how to configure Nacos so you can understand the concepts.

2. Introduce Nacos configuration center

Let’s use eshop-user as an example to demonstrate our configuration center.

2.1. Introduce the nacos-config dependency

<! --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>Copy the code

2.2. Configuration files

Similar to SpringCloud Conig, we must configure it in the bootstrap.yml configuration file, which is invalid in application.yml, and bootstrap.yml takes precedence over Application. yml.

Spring: application: name: user-service # profiles: active: dev # Cloud: nacos: config: enabled:trueIf you don't want to use Nacos for configuration management, set it tofalseCan server - addr:127.0. 01.:8848# Nacos Server address group: DEFAULT_GROUP # group, default DEFAULT_GROUP file-extension: YAMl # Configure content data format, default is propertiesCopy the code

Note: You need to configure Spring.application.name because it forms part of the Nacos configuration management dataId field.

In Nacos Spring Cloud, the full format of dataId is as follows:

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

  • prefixThe default isspring.application.nameIs also available through the configuration itemspring.cloud.nacos.config.prefixTo configure.
  • spring.profile.activeIs the profile corresponding to the current environment.Note: whenspring.profile.activeIf null, the corresponding concatenate-Also will not exist, the dataId concatenation format will become${prefix}.${file-extension}
  • file-exetensionFor the data format of the configuration content, you can pass the configuration itemspring.cloud.nacos.config.file-extensionTo configure. Currently only supportedproperties å’Œ yamlType, default isproperties.

2.3. Create configuration for Nacos Server

Let’s create a new configuration in the configuration list for Nacos Server.

Yaml: Data the Id is user-service.yaml, the default group is used, and the configuration information in YAML format is added.

project:
  name: e-shop-userservice
  author: fighter3
Copy the code

2.4. Control layer

Use Spring’s @value annotation to get configuration information. ${} is the key corresponding to the configuration content of the Nacos configuration center, followed by the default Value.

The configuration is automatically updated via the Spring Cloud native annotation @refreshScope.

/ * * *@Author: Three points of evil *@Date: 2021/5/30
 * @Description: obtain the Nacos configuration item **/

@RefreshScope
@RestController
@RequestMapping("/shop-user")
@api (value = "config info interface ", tags =" config info interface ")
public class NacosConfigController {
    @Value("${project.name:}")
    private String projectName;

    @Value("${project.author:}")
    private String projectAuthor;

    @GetMapping("/config")
    @apiOperation (value = "Get Nacos configuration item ")
    public Map<String, Object> getConfig(a) {
        Map<String, Object> configMap = new HashMap();
        configMap.put("projectName", projectName);
        configMap.put("projectAuthor", projectAuthor);
        returnconfigMap; }}Copy the code

2.5, tests,

Start the user-service service.

Visit knife4j interface address: http://localhost:8080/doc.html, call for Nacos configuration items interface:

Next, we modify the configuration items and publish:

You can see the console print:

Access the configuration interface again:

OK, so now that we have successfully read the configuration of the Nacos configuration center, we will try to unify the configuration of the service, such as the data source, into a centralized configuration.

3. Centralized configuration

Ok, let’s start with the Nacos centralized configuration:

3.1. Create a namespace

We used the default namespace, now we create a new namespace for our development environment configuration. We’ll call it dev_space:

The namespace is used to isolate the configuration, so if we want a test environment configuration, we create a new space.

3.2. Create the data source configuration

Next we create a new configuration user-service-dev.yaml under dev_space

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql: / /localhost: 3306 /shop_user?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
    username: root
    password: root 
Copy the code

3.3. Modify the local configuration

We specify the namespace in bootstrap.yml. The complete bootstrap.yml looks like this:

Spring: application: name: user-service # profiles: active: dev # Cloud: nacos: config: enabled:trueIf you don't want to use Nacos for configuration management, set it tofalseCan server - addr:127.0. 01.:8848# Nacos Server address group: DEFAULT_GROUP # group, default DEFAULT_GROUP file-extension: yaml # config content data format, default: properties namespace: Dev_space # specifies the namespace, default ispublic
Copy the code

Modify application.yml to comment out the data source configuration:

3.4, tests,

Start the user service. After the normal startup of the service, we debug the interface to obtain user information and the interface to obtain configuration respectively.

OK, got the expected result.

Well, that’s the end of Nacos as a distributed configuration center, check out the official documentation for more!

Series of articles continue to be updated!


“Do simple things repeatedly, do repetitive things carefully, and do serious things creatively!” –

I am three points evil, can call me old three/three minutes/three elder brother/three son, a full stack of literary and military development, let’s see next period!



Reference:

[1] : Small column “SpringCloudAlibaba Micro-service Practice”

[2] : NACOS Combat (the most complete in history)

[3] : 4. Spring Cloud Alibaba Nacos Config

[4] : Alibaba Nacos configuration center of Spring Cloud series