Nacos provides users with service infrastructure including dynamic service discovery, configuration management, service management and so on, helping users to build, deliver and manage their micro-service platform more flexibly and easily. Based on Nacos, users can build modern cloud native applications with “service” as the center more quickly. Nacos can seamlessly integrate with Spring Cloud, Kubernetes/CNCF, Dubbo and other microservices ecosystems to provide a better user experience. For more information about Nacos, see the Nacos Project.

Create a project

Create a cloud-nacos-config module and add the spring-cloud-starter-alibaba-nacos-config dependency, pop.xml as follows:


      
<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>
    <parent>
        <artifactId>l-cloud-alibaba</artifactId>
        <groupId>com.codelong</groupId>
        <version>1.0.0</version>
    </parent>

    <artifactId>cloud-nacos-config</artifactId>
    <name>config-service</name>
    <description>Nacos configuration Demo</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

The basic use

Create a new bootstrap.yml configuration file in the Resources directory:

server:
  port: 8081  # Service port number
spring:
  application:
    name: config-service By default, this is also the microservice ID registered in the microservice
  profiles:
    active: dev # environment
  cloud:
    nacos:
      config: # Nacos configuration center configuration
        file-extension: yaml # File extension
        server-addr: 127.0. 01.: 8848
        username: nacos # Nacos username
        password: nacos # Nacos password
Copy the code

Let’s create a new configuration file in the Nacos console

Let’s go back to our project and create a new ConfigController class

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class ConfigController {

    @Value("${message:null}")
    private String message;

    @GetMapping("message")
    public String getMessage(a) {
        return this.message; }}Copy the code

The @refreshScope annotation is used to automatically refresh the configuration, meaning that when we modify the configuration on the Nacos console and click Publish, our application can get the latest configuration without rebooting.

The @value (“${message:null}”) annotation reads the message configuration. The default Value is null.

We start the project, in the browser visit: http://localhost:8081/message:

The nacOS console has read the message to codelong.

Obtaining configuration Rules

The Nacos configuration center uniquely identifies a configuration through namespace, dataId, and Group.

  1. A namespace is a namespace. The default namespace is public. We can create a new namespace in the Nacos console.

  2. DataId is the name of the configuration file. The format of dataId is as follows:

    ${prefix}-${spring.profiles.active}.${file-extension}
    Copy the code
    • prefixThe default ispring.application.nameIs also available through the configuration itemspring.cloud.nacos.config.prefixTo configure;
    • spring.profiles.activeIs corresponding to the current environmentprofile.Note that whenspring.profiles.activeIf null, the corresponding concatenate-Also will not exist, the dataId splicing format becomes${prefix}.${file-extension};
    • file-extensionFor the data format of the configuration content, you can pass the configuration itemspring.cloud.nacos.config.file-extensionTo configure.
  3. Group, namely the configuration packet, the default for DEFAULT_GROUP, by spring. Cloud. Nacos. Config. The group configuration.

So, according to the rules in the above example, we used the name of the spring. The application. The name for the config – service, spring. Cloud. Nacos. Config. The file – the extension of the value of yaml, The value of spring.profiles.active is dev, so dataId is config-service-dev.yaml, grouping is DEFAULT_GROUP by default, and namespace is public by default. This is what we use to create a new configuration in the Nacos console.

Configuration division actual combat

The Namespace, dataId, and Group in the Nacos configuration center can be easily and flexibly divided into configurations. For example, we now have a project to develop named Codeblog. The project developers are divided into two groups: GROUP_A and GROUP_B. The project is divided into three environments: dev, test, and Prod.

If the group leader of GROUP_A now needs to create a codeblog project configuration for the development environment in Nacos, he can do so:

  1. Create a new namespace named codeblog in the Nacos console:

    After the codeblog namespace is created, a namespace ID 48b57993-706B-4CAF-91A4-809DD18125fe is generated that uniquely identifies the namespace.

  2. Create a new configuration in the Nacos console:

  3. Finally, add the following configuration to the codeblog project’s bootstrap.yml configuration file:

    spring:
      profiles:
        active: dev # environment
      cloud:
        nacos:
          config:
            server-addr: 127.0. 01.: 8848
            file-extension: yaml # suffix
            prefix: codeblog # prefix
            namespace: '48b57993-706b-4caf-91a4-809dd18125fe' # namespaces
            group: GROUP_A # corresponding to the group
    Copy the code

Configure a rollback

In Nacos, modifying configuration clicking Publish creates a snapshot of the corresponding historical version, which can be found in the historical version list of the Nacos console:

Click the rollback button to restore the configuration to the specified version.

Get multiple configurations

In addition to specifying a unique configuration as described above, we can also obtain the contents of multiple configuration files at the same time. For example, we can change the bootstrap.yml contents of the project to:

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848
        extension-configs:
          - dataId: ext-config-one.yaml
            group: DEFAULT_GROUP
            refresh: true
          - dataId: ext-config-two.yaml
            group: DEFAULT_GROUP
            refresh: false
Copy the code
  • spring.cloud.nacos.config.extension-configs[n].dataId, specify multiple configurations of dataId, must include file formats, supporting properties, YAML, or YML;
  • spring.cloud.nacos.config.extension-configs[n].group, specify the grouping;
  • spring.cloud.nacos.config.extension-configs[n].refresh, whether refresh is supported.

Ext-config-one. yaml and ext-config-two-. yaml can be refreshed by DEFAULT_GROUP. Ext-config-two-. yaml does not support refreshing.

There is no namespace configuration, which implies that Nacos does not currently support multiple configurations specifying different namespaces.

We create these two configurations in the Nacos console:

Ext-config-one.yaml

ext1: hello
Copy the code

Ext-config-tow.yaml configuration contents:

ext2: world
Copy the code

Add the following to your project’s ConfigController:

@RestController
@RefreshScope
public class TestController {

    @Value("${ext1:null}")
    private String ext1;
    @Value("${ext2:null}")
    private String ext2;

    @GetMapping("multi")
    public String multiConfig(a) {
        return String.format("ext1: %s ext2: %s", ext1, ext2); }... }Copy the code

Start the project, the browser visit: http://localhost:8081/multi:

Change the value of ext1 to nice and ext2 to job:

You can see that ext1 is updated, but ext2 is not.

Multi-configuration sharing

Multi-configuration sharing is similar to obtaining multiple file configurations. Multi-configuration sharing is shown below.

Change the bootstrap.yml configuration to:

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848
        shared-configs: ext-config-one.yaml,ext-config-two.yaml
Copy the code

Spring. Cloud. Nacos. Config. Shared/share configs specifies the ext – config – one. Yaml and ext – config – two yaml configuration.

The configuration print is also available after the request is restarted.

As you can see, whether you share multiple configurations or get multiple configurations, you accomplish the same thing, but both have their limitations. Namespace cannot be specified for multi-configuration sharing. Getting multiple configurations is relatively flexible.

Commonly used configuration

Configuration items key The default value instructions
Server address spring.cloud.nacos.config.server-addr
DataId prefix spring.cloud.nacos.config.prefix spring.application.name
Group spring.cloud.nacos.config.group DEFAULT_GROUP
DataID suffix and content file format spring.cloud.nacos.config.file-extension properties The suffix dataId, which is also the file format for configuration content, currently only supports Properties
Configure how the content is encoded spring.cloud.nacos.config.encode UTF-8 Configured encoding
Gets the configured timeout period spring.cloud.nacos.config.timeout 3000 The unit is ms
The configured namespace spring.cloud.nacos.config.namespace One common scenario is the isolation of configurations for different environments, such as resource isolation for development test environments and production environments.
AccessKey spring.cloud.nacos.config.access-key
SecretKey spring.cloud.nacos.config.secret-key
Relative paths spring.cloud.nacos.config.context-path The relative path of the server API
Access point spring.cloud.nacos.config.endpoint UTF-8 An inbound domain name of a service in a region through which you can dynamically obtain the server address
Whether to enable listening and automatic refresh spring.cloud.nacos.config.refresh-enabled true

Official Example reference

Github.com/alibaba/spr…

Spring – the cloud – alibaba – group. Making. IO/lot – page…