3. Spring Cloud: Nacos Configuration Center

Nacos provides both a registration center and a configuration center. The following two examples are used to illustrate the use of the configuration center.

Table of contents

Case 1: Use of Configuration Center

Manually configure content in Nacos

client use

Case 2: Configuration splitting and reuse

background

Description of configuration splitting and multiplexing

Add dependencies to pom.xml

Delete application.properties and add bootstrap.properties

start up

call verification

Attachment 1: Nacos config client temporary storage directory

Attachment 2: Nacos config isolation hierarchy concept

Attachment 3: Display and write Nacos config configuration center and monitor code examples


Case 1: Use of Configuration Center

Manually configure content in Nacos

Manually defined in Nacos as follows

Data ID:    firstapp-dev.properties

Group  :    DEFAULT_GROUP

配置格式:    Properties

配置内容:   weather=sun
           temperature=20.55

 The command rule of Data ID is: application name-environment profile name.file suffix

  • Application name (Data ID prefix) : The default is ${spring.application.name}, you can also use ${spring.cloud.nacos.config.prefix} to configure
  • Environment profile name : the environment specified by ${spring.profiles.active}. If the environment is not distinguished, the dashed line in front of this content may not exist.
  • File suffix : both the extension of the configuration file in SpringBoot and the configuration format in Nacos.

client use

Create a new project or module. Add nacos-config and bootstrap dependencies to the generated default pom.xml . as follows

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>firstapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>firstapp</name>
    <description>firstapp</description>
    <properties>
        <java.version>1.8</java.version>
        <springcloud.version>3.1.5</springcloud.version>
        <springcloudalibaba.version>2021.0.4.0</springcloudalibaba.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${springcloudalibaba.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.alibaba.nacos</groupId>
                    <artifactId>nacos-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>${springcloudalibaba.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>com.alibaba.nacos</groupId>
                    <artifactId>nacos-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.4.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>${springcloud.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 Create a bootstrap.properties file (stored in the same directory as the application.properties file), and the loading sequence of bootstrap.properties is prior to application.properties.

The content of the bootstrap.properties file is as follows:

spring.application.name=firstapp

#Data ID的前缀(如果不指定,则默认取 ${spring.appliction.name})
spring.cloud.nacos.config.prefix=firstapp
#指定为开发环境
spring.profiles.active=dev
#Nacos配置中心服务端的地址和端口(形式ip:port,ip:port,...) 前个地址不可用时,才会自动重连下一个地址
spring.cloud.nacos.config.server-addr=39.100.80.168:8848
#命名空间(由于Nacos自身Bug:若这里显示指定为public会导致高频刷,不显示指定或者指定其他命名空间均正常。 Bug链接 https://github.com/alibaba/nacos/issues/3460)
#spring.cloud.nacos.config.namespace=public
#配置组(如果不指定,则默认为DEFAULT_GROUP)
spring.cloud.nacos.config.group=DEFAULT_GROUP
#指定文件后缀(如果不指定,则默认为properties)
spring.cloud.nacos.config.file-extension=properties

 For the SpringBoot startup class, add the code to obtain and output configuration items.

@SpringBootApplication
public class FirstappApplication {
    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(FirstappApplication.class, args);
        while (true) {
            String weather = applicationContext.getEnvironment().getProperty("weather");
            String temperature = applicationContext.getEnvironment().getProperty("temperature");
            System.err.println("weather:" + weather + "; temperature: " + temperature);
            TimeUnit.SECONDS.sleep(3);
        }
    }
}

After starting and running, you can see that the SpringBoot program has obtained the value of the Nacos configuration center.

At the same time, if the value of the configuration item is manually adjusted in the Nacos console interface, SpringBoot will automatically obtain the latest value immediately. Because Nacos has an automatic refresh function.

spring.cloud.nacos.config.refresh.enabled=false Auto-refresh can be turned off by configuration 

Case 2: Configuration splitting and reuse

background

This case is based on the previous case ( https://blog.csdn.net/zyplanke/article/details/120849248 ) to modify the registration center.

Description of configuration splitting and multiplexing

Configure the following three Data IDs in nacos:

  • commonshare.properties puts the public configuration of each service
  • paymentService.properties puts the configuration required by the payment service
  • orderService.properties puts the configuration required by the order service

Manually define the above three Data IDs in Nacos, and the contents are as follows:

commonshare.properties:

paymentService.properties:

orderService.properties:

Add dependencies to pom.xml

   ------ 前面省略 ------
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>${springcloudalibaba.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>${springcloud.version}</version>
        </dependency>
   ------ 后面省略 ------

Delete application.properties and add bootstrap.properties

Delete the application.properties files under the payment and order services respectively.

Add a bootstrap.properties file under the payment service, and obtain the configuration of the application from the configuration center instead. The content of bootstrap.properties is as follows:

spring.application.name=payment

#配置中心服务器地址
spring.cloud.nacos.config.server-addr=39.100.80.168:8848
#Data ID的前缀(如果不指定,则默认取 ${spring.appliction.name})
spring.cloud.nacos.config.prefix=paymentService
spring.cloud.nacos.config.group=DEFAULT_GROUP
#指定文件后缀(如果不指定,则默认为properties)
spring.cloud.nacos.config.file-extension=properties
#通用共享配置的信息
spring.cloud.nacos.config.shared-configs[0].data-id=commonshare.properties
spring.cloud.nacos.config.shared-configs[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true

   Add a new bootstrap.properties file under the order service, the content is as follows:

spring.application.name=order

#配置中心服务器地址
spring.cloud.nacos.config.server-addr=39.100.80.168:8848
#Data ID的前缀(如果不指定,则默认取 ${spring.appliction.name})
spring.cloud.nacos.config.prefix=orderService
spring.cloud.nacos.config.group=DEFAULT_GROUP
#指定文件后缀(如果不指定,则默认为properties)
spring.cloud.nacos.config.file-extension=properties
#通用共享配置的信息
spring.cloud.nacos.config.shared-configs[0].data-id=commonshare.properties
spring.cloud.nacos.config.shared-configs[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true

start up

   Start the payment and order services respectively.

   You can see that the payment service startup port is 9999 (port configuration obtained from the nacos configuration center); you can see that the order service startup port is 8888 (port configuration obtained from the nacos configuration center)

call verification

curl http://localhost:8888/consumer/66

The Order service is called successfully, and the returned information meets expectations.

Attachment 1: Nacos config client temporary storage directory

  • The Nacos client will download the configuration from the Nacos server to the local client (if the server configuration changes, it will automatically download the changed configuration to the client local) as a temporary storage of the configuration.
  • The directory where the Nacos client temporarily stores locally is: $HOME /nacos/config/fixed- NacosServerIP _nacos\snapshot\ ($HOME is the HOME path of the client application startup user)

Attachment 2: Nacos config isolation hierarchy concept

  • namespace: It can be used for complete isolation of resources, config configuration resources under different namespaces are not shared, and services are not interoperable (cannot be found). Multi-tenant isolation can be achieved through namespace
  • group: can be used for resource grouping. Under the same namespace, config configuration resources of different groups are not shared. Services do not interoperate (cannot be found). Different environments can be isolated through groups
  • cluster_name: In the Nacos config configuration center, there is no such concept. Belonging to the Service Registry Concept

Note 1: The groups of the registration center and the configuration center are different, and each has its own management.

Note 2: For the settings of the above layers, different groups can be configured in the Nacos registration center and configuration center for the same service instance. That is to say, the same service declares group=A when obtaining configuration from Nacos, and declares group=B when registering the service with Nacos, which is allowed.

More about nacos config configuration items in springcloud can be found on nacos official website:

Nacos config · alibaba/spring-cloud-alibaba Wiki · GitHub

Attachment 3: Display and write Nacos config configuration center and monitor code examples

Write and publish the configuration content displayed in the Java code to the configuration center

    a. Instead of using the Springboot Bean method, directly access the Nacos server through the following methods, write configuration to the server, or read configuration:

ConfigService configService = NacosFactory.createConfigService(ServerAddrList);
configService.publishConfig("test.properties", "GJS_GROUP" , "aaa.bbb=111\nccc.ddd=222\nxxx=333");
configService.getConfig(String dataId, String group, long timeoutMs);
configService.shutDown();

   b. If in the Springboot Bean, the configService object is obtained through automatic injection:

@Autowired
NacosConfigManager nacosConfigManager;


...... 省略 ......
     ConfigService configService = nacosConfigManager.getConfigService();
...... 然后使用该对象操作(省略)......

Add configuration item monitoring for Nacos configuration center in Java code

    Register a listener with the Nacos configuration center. When the configuration content of the Nacos configuration center changes, the latest content is automatically obtained through this listener, and the variables of this class are updated and saved:

/**
 * 向Nacos配置中心注册监听器
 * 当Nacos配置中心的配置内容变化时,通过此监听器自动获取最新内容,并更新并保存本类变量中
 *
 */
@Component
@Slf4j
public class NacosConfigListener {

    public static Map<String, String> exchCodeServiceNameMap = new HashMap<>(2000);

    @Autowired
    private void addNacosConfigListener(NacosConfigManager nacosConfigManager) {
        ConfigService configService = nacosConfigManager.getConfigService();
        try {
            configService.addListener(Global.NacosConfigDataID_ExchCode_ServiceName_Map, Global.NacosConfigGroup_ExchCode_ServiceName_Map,
                    new PropertiesListener() {
                        @Override
                        public void innerReceive(Properties properties) {
                            properties.forEach((key, value) -> exchCodeServiceNameMap.put( (String) key, (String)value));
                            log.info("感知到Nacos配置中心dataID=[{}],group=[{}]发生变化,已将最新配置内容更新至本地对象", Global.NacosConfigDataID_ExchCode_ServiceName_Map,Global.NacosConfigGroup_ExchCode_ServiceName_Map );
                        }
                    });
            log.info("作向Nacos配置中心注册器(监听配置变化)完成");
        } catch (NacosException e) {
            log.error("监听Nacos配置中心遇到异常", e);
        }
    }
}

Guess you like

Origin blog.csdn.net/zyplanke/article/details/120860958