NACOS dynamic configuration

Posted by dkim777 on Mon, 25 Oct 2021 10:46:48 +0200

1, Introduction to Nacos configuration center

Nacos provides two services, one is the Naming Service for service registration and discovery, and the other is the Config Service for configuration center and dynamic configuration. Their bottom layers are supported by the core module. The outer layer provides OpenAPI for clients, and provides User Console and Admin Console for users to use. Nacos does not push the latest configuration information of the server to the client, but the client maintains a long polling task, regularly pulls the changed configuration information, and then pushes the latest data to the Listener holder.

The configuration has the following characteristics:

Configuration is a read-only variable independent of the program
The configuration is read-only for the program. The program changes its behavior by reading the configuration, but the program should not change the configuration
Configure the entire life cycle that accompanies the application
Configuration runs through the entire life cycle of the application. The application is initialized by reading the configuration at startup, and the behavior is adjusted according to the configuration at runtime. For example, the port number of the service needs to be read at startup, and the system needs to read the timing policy and execute timing tasks during operation.

Configuration can be loaded in a variety of ways:

Common programs include internal hard code, configuration files, environment variables, startup parameters, database-based, etc
Configuration needs governance
The same program often needs different configurations in different environments (development, testing, production) and different clusters (such as different data centers), so it needs perfect environment and cluster configuration management

2, Configuration center construction

1. Project configuration

POM package for importing Nacos config:

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

2.yml configure NACOS system information

The bootstrap.yml file is added, and the configuration information is written in this file, because springboot will start first
bootstrap.yml (bootstrap.properties) is used to execute during program boot, and is used to read earlier configuration information. For example, it can be used to configure parameters used in application.yml
application.yml (application.properties) is application specific configuration information, which can be used to configure public parameters to be used in subsequent modules.
Loading order: bootstrap. YML > application. YML > Application dev (prod). YML >

Add application.name and nacos config information in bootstrap.yml:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.8.150:8848
        namespace: 7e6872ef-3933-499c-a88a-505bc90a4bab
      config:
        server-addr: 192.168.8.150:8848
        file-extension: yml # Here is the suffix used for configuration
        group: DEFAULT_GROUP
        namespace: 7e6872ef-3933-499c-a88a-505bc90a4bab # The content of the namespace is the id of the gene namespace configured in nacos.
        shared-dataids: miracle-config.yaml

application.yml configuration:

server:
  port: 8099


spring:
  application:
    name: miracle-system
  profiles:
    active: gene

3. New dynamic configuration parameters of Nacos system

Add namespace first:
It is better to correspond to spring.profiles.active in the application.yml configuration, and record the namespace ID for subsequent needs

New configuration in configuration center:


Create a new configuration in Nacos server, where the definition rule of Data ID is: p r e f i x − {prefix}- prefix−{spring.profiles.active}.${file-extension}

Prefix defaults to the value of spring.application.name, which can also be configured through the configuration item spring.cloud.nacos.config.prefix.

Spring.profiles.active is the profile corresponding to the current environment, which can be configured through the configuration item spring.profiles.active.

File exception is the data format of the configuration content, which can be configured through the configuration item spring.cloud.nacos.config.file extension. Currently, only properties and yaml types are supported.

Be sure to select your corresponding type, your file yaml type, but if you select properties, an error will be reported.

be careful:
1. When spring.profiles.active is empty, the corresponding connector - will not exist, and the splicing format of dataId will become prefix. {prefix}. Prefix. {file extension}

2. When creating a configuration file, the suffix of Data ID needs to be consistent with the configuration format
The code defaults to properties; the code needs to be consistent with the Data ID when referencing
The difference from Spring Boot is that the Data ID here must specify the corresponding suffix

The project name in my application.yml is miracle system
The namespace is: gene
The file suffix is: yml
So my Data ID is as follows:

miracle-system-gene.yml

This place is prone to configuration errors. We must pay attention to it.

4. Code configuration

Official examples:
Java mode:

package pers.miracle.miraclecloud.system.utils;

import java.util.Properties;
import java.util.concurrent.Executor;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
/**
 * @author lgn
 * @version 1.0
 * @date 2021/10/25 10:27
 */
public class NacosConfigExample {

    /**
     *
     * @param args
     * @throws NacosException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws NacosException, InterruptedException {
        String serverAddr = "192.168.8.150:8848";
        String dataId = "miracle-system-gene.yml";
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("recieve:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        boolean isPublishOk = configService.publishConfig(dataId, group, "content");
        System.out.println(isPublishOk);

        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);

        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println(isRemoveOk);
        Thread.sleep(3000);

        content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        Thread.sleep(300000);

    }
}

result:

spring cloud mode:
Add the @ refreshscope annotation in the controller using the configuration and the @ Value("${Key name}") annotation on the injection attribute. The @ refreshscope keyword ensures that the configuration can be refreshed in real time. Just annotate on the controller layer or the class where the value to be refreshed is located.

package pers.miracle.miraclecloud.system.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author lgn
 * @version 1.0
 * @date 2021/10/25 10:51
 */
@RestController
@RequestMapping("/nacos/nacosHelper")
@RefreshScope
public class NacosController {

    @Value("${common.name}")
    private String name;

    @Value("${common.info}")
    private String info;

    @RequestMapping("/getNacosInfo")
    public String get() {
        return "Entertainment heavy exposure:"+name+info;
    }
}

1. If you use the configuration file in yaml format, you must pay attention to the writing format configured in Nocos and pay attention to spaces. If you do not enter spaces,
If @ Value("common.name") is used, the corresponding configuration parameters will not be found, and an error will be reported when starting the service
It was unexpectedly found in the attempt that @ Value("common:name") can be used to obtain configuration parameters, and the obtained string is name: Zhang
Error example:

common:
   name:Kris

Correct example:

common:
   name: Kris
   info: Big bowl of wide noodles!

Visit:

Modify the parameters in nacos to see if they change again:


You can see that it has changed

Topics: Java Spring Cloud