Nacos configuration center

Posted by Yippee on Tue, 04 Feb 2020 12:42:35 +0100

The configuration of Nacos configuration center can be obtained by Namespace, group and Data ID to locate a configuration set.

1. Configuration set (Data ID)

In a system, a configuration file is usually a configuration set. A configuration set can contain various configuration information of the system. For example, a configuration set may contain configuration items such as data source, thread pool, log level, etc. Each configuration set can define a meaningful name, that is, the ID of the configuration set, that is, the Data ID.

Configuration item

Configuration items are the configuration contents contained in the configuration set. It represents a specific configurable parameter and its value field, usually in the form of key=value. For example, the log output level (loglevel = info|||||||||||||||||||||||||.

2. Configure groups

Configuration grouping is the grouping of configuration sets. It is represented by a meaningful string (such as Buy or Trade). Different configuration groups can have the same configuration set (Data ID). When you create a configuration on Nacos, if you do not fill in the name of the configuration group, the default name of the configuration group is default Ou group. Common scenario of configuration grouping: it can be used to distinguish different projects or applications. For example, the configuration set of student management system can define a group as: student group.

Note: default group is used by default.

3. Namespace (Namespace)

Namespace can be used for configuration isolation of different environments. For example, development environment, test environment and production environment can be isolated, because their configurations may be different, or different users can be isolated. Different developers use the same nacos to manage their configurations, which can be isolated through namespace. Under different namespaces, there can be configuration groups or configuration sets with the same name.

When a namespace is called by code, it uses the ID of the namespace. When creating a namespace, Nacos will create an ID for each namespace, as shown in the figure:

Note: public namespace is used by default.

4. Best practices

Nacos abstractly defines the concepts of Namespace, Group and Data ID. what these concepts represent depends on what we regard them as. Here is a recommended usage:

Namespace: represents different environments, such as development, testing, and production.

Group: for a project, such as XX medical project, XX e-commerce project

DataId: there are often several projects under each project, and each configuration set (DataId) is the main configuration file of a project

5. Code call:

Test case code block:

package com.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author Jay
 * @version 1.0
 **/
public class demoMain {
    public static void main(String[] args) throws NacosException {
        //Using nacos client to obtain configuration information on nacos service remotely
        //nacos server address
        String serverAddr = "127.0.0.1:8848";
        //data id
        String dataId = "nacos-simple-demo.yaml";
        //group
        String group = "DEFAULT_GROUP";

        //namespace
        String namespace = "c67e4a97-a698-4d6d-9bb1-cfac5f5b51c4";
        Properties properties =new Properties();
        properties.put("serverAddr",serverAddr);
        properties.put("namespace",namespace);
        //Get configuration
        ConfigService configService = NacosFactory.createConfigService(properties);
        // String dataId, String group, long timeoutMs
        String config = configService.getConfig(dataId, group, 5000);
        System.out.println(config);
        //String dataId, String group, Listener listener
        configService.addListener(dataId, group, new Listener() {
            public Executor getExecutor() {
                return null;
            }
            //Get notification when configuration changes
            public void receiveConfigInfo(String s) {
                System.out.println(s);
            }
        });

        while (true){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

Integrate spring cloud code block:

Because the spring boot loading order is bootstrap > application, the information using configuration center should be configured in bootstrap. (step on the pit!)

server:
  port: 9999

spring:
  application:
    name: serviceName
  cloud:
    nacos:
      config:
        #enabled: false
        server-addr: 192.168.83.129:8848
        file-extension: yaml
        namespace: 1969d1e1-1c46-43ea-b57c-af75a7f8aad9
        group: DEV_GROUP

Note: the name of Data Id is the name of application plus file extension, which is serviceName.yaml. The type of file extension needs to be defined according to the file type on Nacos.

java code:

package com.nacos.service1.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NacosConfigController {

    @Value("${trussan.host}")
    private String config1;

    @GetMapping("/configs")
    public String getConfigs(){

        return config1;
    }
}

In this way, however, when the configuration information on Nacos is modified, the value obtained by the server will not change due to the annotation of spring @value. Therefore, it is recommended to use the following way to obtain the configuration information in production:

package com.nacos.service2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NacosConfigController {

    @Autowired
    ConfigurableApplicationContext applicationContext;

    @GetMapping("/configs")
    public String getConfigs(){

        return applicationContext.getEnvironment().getProperty("config.service");
    }
}

Inject the configuration of the context and obtain it dynamically.

Published 16 original articles, won praise 2, visited 90000+
Private letter follow

Topics: Spring Java