Spring Cloud Alibaba 7 training camp - distributed configuration the next day

Spring Cloud Alibaba distributed configuration

1. Introduction

Nacos provides key/value storage for storing configuration and other metadata, and provides server-side and client-side support for externalized configuration in distributed systems. Using Spring Cloud Alibaba Nacos Config, you can centrally manage the external attribute configuration of your Spring Cloud application in the Nacos Server.

Spring Cloud Alibaba Nacos Config is an alternative to Config Server and Client. The concepts on the Client and server are consistent with the abstraction of Spring Environment and PropertySource. In the special bootstrap stage, the configuration is loaded into the Spring Environment. When an application goes through the deployment pipeline from development to test to production, you can manage the configuration between these environments and ensure that the application has everything it needs to run when migrating. The acquisition and startup methods of Nacos can be referred to Nacos official website.

Note: if the reader is a user of Alibaba cloud commercial component ANS or ACM, please use Nacos Config instead of the corresponding component.

2. Learning objectives

  • Use Nacos Config as Spring Cloud distributed configuration
  • Dynamic refresh of Bean using Nacos Config
  • Learn about Nacos Config advanced configuration

3. Details

  • Quick start: use Nacos Config as the external configuration source
  • Multi file extension support: take YAML file extension as an example to discuss Nacos Config multi file extension support
  • Dynamic configuration update: demonstrate the @ RefreshScope feature to realize dynamic refresh of beans
  • Custom extension: customize the configuration extension of namespace, Group and Data Id
  • Operation and maintenance features: demonstrate the advanced external configuration of Nacos Config and the internal details of Endpoint

4. Get started quickly

4.1 how to introduce Nacos Config to support distributed configuration

There are also two ways to introduce Nacos Config, namely Aliyun Java Initializr and Maven POM XML dependency. It is officially recommended to use Aliyun Java Initializr to introduce Nacos Discovery in order to simplify the dependencies between components.

4.1.1 [lazy] directly check the application code in the sandbox

Click link , directly access the sandbox environment. Here will be the case code prepared for you ^ ^ ^.

4.1.2 [simple] create a project through Aliyun Java Initializr and introduce Nacos Config (recommended)

Due to the complexity of the version and dependency of Spring Cloud components, readers are recommended to use Aliyun Java Initializr to build application projects.
Readers choose their preferred Web browser to visit Aliyun Java Initializr, whose resource website is: https://start.aliyun.com/bootstrap.html

Take Google Chrome browser as an example. After the web page is loaded, first enter Group: "com.alibaba.cloud" and Artifact: "Nacos Config sample" in the "project basic information" section. Then, search for "Nacos Config" in the "component dependency" input box and select "Nacos Configuration", as shown below:

As above, add "Spring Web" and "Spring Boot Actuator" components:

After selecting components, click the "generate" highlight button. Then, the platform will generate a compressed file named "Nacos config sample. Zip", save it to the local directory, unzip the file, and the project directory will be generated. Open pom.com in the directory XML file, it is not difficult to find the Nacos starter declaration (the following XML contents are from the pom.xml file in the project root path):

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

However, the starter does not specify a version. The specific version is stated on www alibaba. Cloud: spring cloud Alibaba dependencies:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Among them, ${Spring Cloud Alibaba. Version} and ${Spring Boot. Version} are the dependent versions of Spring Cloud Alibaba and Spring Boot components respectively. Their versions are defined in the < Properties > element, i.e., 2.2.1 Release # and # 2.3.0 RELEASE:

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>
        <spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
    </properties>

If readers are familiar with the configuration of Maven dependency management, they can consider Maven POM XML depends on Nacos Config.

4.1.3 [advanced] through Maven POM XML depends on Nacos Config

If you want to use Nacos to realize service registration / discovery in your project, use group ID {com alibaba. The cloud and artifact ID s are spring cloud starter Alibaba Nacos config starters.

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

This declaration method also needs to declare # com alibaba. Cloud: spring cloud Alibaba dependencies. The content is the same as that in the previous section and will not be repeated here. The next section discusses how to use Nacos Config to support distributed configuration.

4.2 using Nacos Config to realize distributed configuration

Using Nacos Config to realize distributed configuration is very similar to that of spring cloud consult and Spring Cloud Zookeeper. You only need to add relevant externalized configuration to work. In other words, Nacos Config will not invade the application code to facilitate application integration and migration. If readers are familiar with the use of spring cloud consult or Spring Cloud Zookeeper, they usually need to pre deploy the consult or Zookeeper service process, and so does Nacos Config.

4.2.1 start the Nacos server

We provide developers with a set of free Nacos Server: access http://139.196.203.133:8848/nacos/ Check the console (the account name / password is Nacos configuration / Nacos configuration) and select "configuration management / configuration list":

Since the service is public and free, in order to do a good job of isolation, please select the function of distributed configuration to operate under the namespace of sandbox configuration.

Specific startup mode reference Nacos official website.
For more versions of Nacos Server, you can release page Download the latest version.

4.2.2 add Nacos configuration

Click the "+" sign on the right side of the "configuration list" page (indicated by the red arrow):

The browser jumps to a new page and fills in the following contents:

Among them, the Data ID consists of the application name (Nacos config sample) + the file suffix (. properties). Click the "publish" button (indicated by the red arrow), and the configuration content is:

user.name=nacos-config-sample
user.age=90

After publishing successfully, a prompt pop-up box will appear on the console.

Special reminder

The application name in the Data ID in the picture uses Nacos config sample. If we use the Nacos Server provided by us, there may be application name conflict due to multiple users using it at the same time. It is suggested to change it to an application name that does not duplicate others:
spring.application.name=xxxxxx
Replace the xxxxx section above

4.2.3 configure Nacos Config Server address

Go back to the application Nacos config sample project, create a new file named "bootstrap.properties" in the resources directory, and configure the following contents:

spring.cloud.nacos.config.server-addr=139.196.203.133:8848
spring.cloud.nacos.config.username=nacos-configuration
spring.cloud.nacos.config.password=nacos-configuration
spring.cloud.nacos.config.namespace=sandbox-configuration

Note that the Nacos Server address must be configured in bootstrap Properties file.

Note that when you use a domain name to access Nacos, spring cloud. nacos. config. The configuration method of server addr is domain name: port. For example, the domain name of Nacos is ABC com. Nacos, the listening port is 80, then spring cloud. nacos. config. server-addr=abc.com.nacos:80. Note that port 80 cannot be omitted.

4.2.4 add read Nacos Config implementation

Modify the Nacos config sample boot class as follows:

@SpringBootApplication
public class NacosConfigSampleApplication {

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

    @Value("${user.age}")
    private int userAge;

    @PostConstruct
    public void init() {
        System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
    }

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigSampleApplication.class, args);
    }
}

4.2.5 start the Nacos Config application

Run the Nacos config sample boot class Nacos configsampleapplication and observe the console results (intercept Key log information):

[init] user name : nacos-config-sample , age : 90

If you start the application in the sandbox, because you can't see the running log temporarily, you can view the parameters through the WEB controller. See Section 5.1 for specific operations.

5. Use Nacos Config to realize dynamic refresh of Bean

Nacos conf supports standard Spring Cloud @RefreshScope Feature, that is, after the application subscribes to a Nacos configuration, when the configuration content changes, the properties of the binding configuration in Refresh Scope Beans will be conditionally updated. The so-called condition means that a Bean must:

  • Required condition: the declaration class of Bean must be marked with @ RefreshScope
  • One of two conditions:
  • Attribute (non static field) annotated with @ Value
  • @ConfigurationPropertiesBean

In addition, Nacos conf has also introduced the Nacos Client underlying data change monitoring interface, i.e alibaba. nacos. api. config. listener. Listener. The following content will discuss these three different usage scenarios respectively.

Nacos Client: Nacos Client API, which is also the underlying dependency of Nacos Config

5.1 using Nacos Config to dynamically refresh the Bean @ Value attribute

Based on the modification of application Nacos config sample, mark the boot class NacosConfigSampleApplication with @ RefreshScope and @ RestController, so that this class becomes a Spring MVC REST controller with dynamic refresh capability. The specific code is as follows:

@SpringBootApplication
@RestController
@RefreshScope
public class NacosConfigSampleApplication {

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

    @Value("${user.age}")
    private int userAge;

    @PostConstruct
    public void init() {
        System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
    }

    @RequestMapping("/user")
    public String user() {
        return String.format("[HTTP] user name : %s , age : %d", userName, userAge);
    }

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigSampleApplication.class, args);
    }
}

Restart the boot class NacosConfigSampleApplication, and the console output is as follows:

[init] user name : nacos-config-sample , age : 90

Then access the REST resource / user through the command line:

% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 90

If the sandbox environment is used, please directly click the access button in the application list and add / user in the address bar of the open browser window, as shown in the following figure:


In this article, other steps based on http access are similar and will not be repeated later

The user name and age data in the request result are consistent with those in the application startup, because the configuration data in the Nacos Server has not changed at this time.
Then, adjust the Nacos config sample through the Nacos console Properties configuration, set user Age changed from 90 to 99:

Click the "publish" button to observe the changes in the application log (some contents are omitted):

c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=4a8cb29154adb9a0e897e071e1ec8d3c, content=user.name=nacos-config-sample
user.age=99, type=properties
o.s.boot.SpringApplication               : Started application in 0.208 seconds (JVM running for 290.765)
o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [user.age]
  • The first and second lines of code are output by the Nacos Client to inform the developer of specific content changes. It is not difficult to find that there is no complete configuration content output here, only the changed part, that is, configure user age.
  • The log in line 3 seems to restart the spring application, but it takes a short time. I won't explain it here for the moment. I'll discuss it in detail later. Just know that it is related to the Bootstrap application context.
  • The last line of log is output by the Spring Cloud framework, prompting developers to change the Spring configuration Property. There may be multiple, but this example only modifies one, so a single one is displayed.

Next, revisit the REST resource / user:

% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 99

The terminal log shows that this configuration change is synchronized to the contents of the @ Value("${user.age}") attribute userAge. In addition to this console, the following content is also applied:

[init] user name : nacos-config-sample , age : 99

The log is output by the init() method. Does it mean that the method was called by the framework? The answer is yes. Since the @ PostConstruct method is executed, will the @ PreDestroy method be called? You may wish to add the Spring Bean destruction callback method:

@SpringBootApplication
@RestController
@RefreshScope
public class NacosConfigSampleApplication {

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

    @Value("${user.age}")
    private int userAge;

    @PostConstruct
    public void init() {
        System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
    }
    
    @PreDestroy
    public void destroy() {
        System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
    }

    ...
}

Restart the boot class NacosConfigSampleApplication again, and the initialization log still outputs:

[init] user name : nacos-config-sample , age : 99

User. Will be configured Adjust the age content from 99 to 18, and observe the change of console log:

c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=e25e486af432c403a16d5fc8a5aa4ab2, content=user.name=nacos-config-sample
user.age=18, type=properties
o.s.boot.SpringApplication               : Started application in 0.208 seconds (JVM running for 144.467)
[destroy] user name : nacos-config-sample , age : 99
o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [user.age]

Compared with the previous version, the log inserts the output of the destroy() method, and the Bean attribute userAge is still the data before the change. Then, access the REST resource / user again, where the terminal log:

% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 18

Application console log:

[init] user name : nacos-config-sample , age : 18

There is no difference between the two versions and the previous version, but the new version gives a phenomenon, that is, when Nacos Config receives the server configuration change, the corresponding @ RefreshScopeBean life cycle callback method will be called, destroyed first, and then re initialized. This example is designed in this way to remind readers to be aware of the impact of the configuration change of @ Nacos Config on the callback method of @ RefreshScopeBean life cycle and avoid repeated initialization and other operations.

Note: the Nacos Config configuration change calls the Spring Cloud API contextrefresh, which will perform the above behavior. Similarly, executing Spring Cloud Acutator Endpoint refresh will also use context refresher.

Through the above discussion, it is believed that readers have been quite familiar with the Nacos configuration change operation, and the relevant configurations will not be repeated later. Next, continue to discuss the scenario of @ ConfigurationPropertiesBean.

5.2 dynamic refresh of @ ConfigurationPropertiesBean property using Nacos Config

Add a new User class in the application of Nacos config sample, and mark @ RefreshScope and @ ConfigurationProperties. The code is as follows:

@RefreshScope
@ConfigurationProperties(prefix = "user")
public class User {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

According to the definition of @ ConfigurationProperties, the property of the user class is bound to the configuration property prefix user. Next, adjust the boot class. The code is as follows:

@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {

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

    @Value("${user.age}")
    private int userAge;

    @Autowired
    private User user;

    @PostConstruct
    public void init() {
        System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
    }

    @PreDestroy
    public void destroy() {
        System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
    }

    @RequestMapping("/user")
    public String user() {
        return "[HTTP] " + user;
    }

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigSampleApplication.class, args);
    }
}

Compared with the previous version, NacosConfigSampleApplication is implemented. The main changes are as follows:

  • Activate @ ConfigurationPropertiesBean @ EnableConfigurationProperties(User.class)
  • Inject @ UserBean through @ Autowired dependency
  • Replace the implementation in user() with the user bean (tostring() method

Next, restart the application and then set user The age configuration is adjusted from 18 to 99, and the console log output meets the expectations:

[init] user name : nacos-config-sample , age : 18
......
[fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=b0f42fac52934faf69757c2b6770d39c, content=user.name=nacos-config-sample
user.age=90, type=properties
......
[destroy] user name : nacos-config-sample , age : 18
o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [user.age]

Next, access the REST resource / user and observe the terminal log output:

% curl http://127.0.0.1:8080/user
[HTTP] User{name='nacos-config-sample', age=90}

The User Bean attribute was successfully changed to 90 to achieve the actual combat effect. The previous section mentioned that the change of Nacos Config configuration will affect the life cycle method callback of @ RefreshScopeBean. Similarly, if you add initialization and destruction methods for , User, there will also be text. However, this time, , User will implement the Spring standard life cycle interfaces , InitializingBean and , DisposableBean:

@RefreshScope
@ConfigurationProperties(prefix = "user")
public class User implements InitializingBean, DisposableBean {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("[afterPropertiesSet()] " + toString());
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("[destroy()] " + toString());
    }
}

After the code is adjusted, restart the application, modify the configuration (90 - > 19), and observe the console log output:

[init] user name : nacos-config-sample , age : 90
......
c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=30d26411b8c1ffc1d16b3f9186db498a, content=user.name=nacos-config-sample
user.age=19, type=properties
......
[destroy()] User{name='nacos-config-sample', age=90}
[afterPropertiesSet()] User{name='nacos-config-sample', age=19}
[destroy] user name : nacos-config-sample , age : 90
......
o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [user.age]

It is not difficult to find that the life cycle method of UserBean is not only called, but also destroyed first and then initialized. So, is this phenomenon related to the restart of spring application seen before? The answer is yes, but we will discuss it later.

The next section will continue to discuss how to use the underlying Nacos configuration monitoring to realize the dynamic refresh of Bean attributes

5.3 using Nacos Config to monitor and realize dynamic refresh of Bean attributes

As mentioned earlier, @ com alibaba. nacos. api. config. listener. Listener is the standard configuration listener interface of the Nacos Client API. It only listens to the configuration content and cannot directly connect with the Spring system. Therefore, it is necessary to use the Spring Cloud Alibaba Nacos Config API nacosconfigmanager (thanks to the coder contribution of little partners liaochuntao and zkzlx). The code adjustment is as follows:

@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {

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

    @Value("${user.age}")
    private int userAge;

    @Autowired
    private User user;

    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Bean
    public ApplicationRunner runner() {
        return args -> {
            String dataId = "nacos-config-sample.properties";
            String group = "DEFAULT_GROUP";
            nacosConfigManager.getConfigService().addListener(dataId, group, new AbstractListener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("[Listener] " + configInfo);
                }
            });
        };
    }

    @PostConstruct
    public void init() {
        System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
    }

    @PreDestroy
    public void destroy() {
        System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
    }

    @RequestMapping("/user")
    public String user() {
        return "[HTTP] " + user;
    }

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigSampleApplication.class, args);
    }
}

Major code changes:

  • @Autowired dependency injection NacosConfigManager
  • Add a new # runner() method to obtain # ConfigService through # NacosConfigManagerBean, and add the implementation of # abstractlistener (Listener abstract class) to listen to the configuration contents of dataId = "Nacos config sample. Properties" and group = "DEFAULT_GROUP"

Restart the application and configure user Adjust the age from 19 to 90 and observe the log changes:

c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=b0f42fac52934faf69757c2b6770d39c, content=user.name=nacos-config-sample
user.age=90, type=properties
[Listener] user.name=nacos-config-sample
user.age=90
......

Under the log in line 1, the output content of the monitoring implementation code is added, but this content is the complete configuration, not the changed content. Readers should pay attention to the differences. The next step is to map the configuration to Bean attributes. Here is a simple solution. There are two implementation steps:

  • Convert String content to Properties object
  • Set the Properties property value to the corresponding Bean property

The code is adjusted as follows:

@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {
    
    ......

    @Bean
    public ApplicationRunner runner() {
        return args -> {
            String dataId = "nacos-config-sample.properties";
            String group = "DEFAULT_GROUP";
            nacosConfigManager.getConfigService().addListener(dataId, group, new AbstractListener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("[Listener] " + configInfo);
                    System.out.println("[Before User] " + user);

                    Properties properties = new Properties();
                    try {
                        properties.load(new StringReader(configInfo));
                        String name = properties.getProperty("user.name");
                        int age = Integer.valueOf(properties.getProperty("user.age"));
                        user.setName(name);
                        user.setAge(age);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("[After User] " + user);
                }
            });
        };
    }

    ......
        
}

Restart the application and configure user Adjust the age from 90 to 19 and observe the log changes:

[Listener] user.name=nacos-config-sample
user.age= 19
[Before User] User{name='nacos-config-sample', age=90}
[After User] User{name='nacos-config-sample', age=19}

The above three examples focus on the dynamic update of Bean properties based on Nacos Config, but they are the use scenarios of Spring Cloud. If the reader's application only uses Spring or Spring Boot, you can consider the Nacos Spring project. Github address: https://github.com/nacos-group/nacos-spring-project Where @ NacosValue supports the update of attribute granularity.

6. Advanced configuration of Nacos config

6.1 support custom namespace configuration

First, let's take a look at the concept of Nacos Namespace Nacos concept
Used for tenant granularity configuration isolation. Under different namespaces, there can be configurations of the same Group or Data ID. One of the common scenarios of Namespace is to distinguish and isolate the configurations of different environments, such as the isolation of resources (such as configuration and service) between development and test environment and production environment.
If the ${spring.cloud.nacos.config.namespace} configuration is not explicitly specified, the Public namespace on Nacos is used by default. If you need to use a custom namespace, you can implement it through the following configuration:

spring.cloud.nacos.config.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7

Note: this configuration must be placed in bootstrap Properties file. In addition, spring cloud. nacos. config. The namespace value is the id corresponding to the namespace. The id value can be obtained on the console of Nacos. When adding configurations, be careful not to select other namepages, otherwise you will not be able to read the correct configuration

6.2 support custom Group configuration

Default is used by default when the ${spring.cloud.nacos.config.group} configuration is not explicitly specified_ GROUP . If you need to customize your own group, you can configure it as follows:

spring.cloud.nacos.config.group=DEVELOP_GROUP

Note: this configuration must be placed in bootstrap Properties file. When adding configuration, the value of Group must be the same as that of spring cloud. nacos. config. The configuration values of Group are consistent.

6.3 Data Id configuration supporting custom extension

After configuring Alibaba cloud ID 1.0, Alibaba cloud 2 can be customized. The detailed design of this part can be referred to here . A complete configuration case is as follows:

spring.application.name=opensource-service-provider
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# config external configuration
# 1. Data Id in default group DEFAULT_GROUP, dynamic refresh of configuration is not supported
spring.cloud.nacos.config.extension-configs[0].data-id=ext-config-common01.properties
# 2. Data Id is not in the default group and dynamic refresh is not supported
spring.cloud.nacos.config.extension-configs[1].data-id=ext-config-common02.properties
spring.cloud.nacos.config.extension-configs[1].group=GLOBALE_GROUP
# 3. The Data Id is not in the default group and supports dynamic refresh
spring.cloud.nacos.config.extension-configs[2].data-id=ext-config-common03.properties
spring.cloud.nacos.config.extension-configs[2].group=REFRESH_GROUP
spring.cloud.nacos.config.extension-configs[2].refresh=true

You can see:

  • Through spring cloud. nacos. config. extension-configs[n]. Data Id configuration method to support the configuration of multiple data IDs.
  • Through spring cloud. nacos. config. extension-configs[n]. The configuration method of group is to customize the group where the Data Id is located. If the configuration is not clear, the default is DEFAULT_GROUP.
  • Through spring cloud. nacos. config. extension-configs[n]. Refresh configuration method to control whether the Data Id can be refreshed dynamically in the application and perceive the latest configuration value when the configuration is changed. Default is not supported.

Note: when multiple data IDs are configured at the same time, their priority relationship is spring cloud. nacos. config. extension-configs[n]. Data Id where the greater the value of N, the higher the priority.
spring. cloud. nacos. config. extension-configs[n]. The value of Data Id must have a file extension. The file extension can support both properties and yaml/yml. Spring cloud. nacos. config. The configuration of file extension has no effect on the Data Id file extension of the custom extension configuration.

By customizing the extended Data Id configuration, you can not only solve the problem of configuration sharing among multiple applications, but also support an application with multiple configuration files.
In order to more clearly configure the shared Data Id among multiple applications, you can configure it in the following ways:

# Configure shared Data Id
spring.cloud.nacos.config.shared-configs[0].data-id=common.yaml
# Default Data Id, default data_ GROUP
spring.cloud.nacos.config.shared-configs[0].group=GROUP_APP1
# Whether to dynamically refresh the configuration Data Id when the configuration is changed. The default is false
spring.cloud.nacos.config.shared-configs[0].refresh=true

You can see:

  • Through spring cloud. nacos. config. shared-configs[n]. Data Id to support the configuration of multiple shared data IDs.
  • Through spring cloud. nacos. config. shared-configs[n]. Group to configure the group where the user-defined Data Id is located. If the configuration is not clear, the default is DEFAULT_GROUP.
  • Through spring cloud. nacos. config. shared-configs[n]. Refresh to control whether the Data Id supports dynamic refresh in the application when the configuration is changed. The default is false.

6.4 priority of configuration

Spring Cloud Alibaba Nacos Config currently provides three configuration capabilities to pull relevant configurations from Nacos.

  • A: Through spring cloud. nacos. config. shared-configs[n]. Data Id supports the configuration of multiple shared data IDs
  • B: Through spring cloud. nacos. config. extension-configs[n]. The Data Id method supports the configuration of multiple extended data IDs
  • C: Relevant Data Id configuration is automatically generated through internal relevant rules (application name, application name + Profile)

When the three methods are used together, one of their priority relationships is: a < B < C

6.5 complete shutdown configuration

By setting spring cloud. nacos. config. Enabled = false to completely close Spring Cloud Nacos Config

6.6 more advanced configurations

More configuration items about Nacos Config Starter are as follows:

Configuration item Key Default value explain
Server address spring.cloud.nacos.config.server-addr   The ip address and port on which the Nacos Server starts listening
Configure the corresponding DataId spring.cloud.nacos.config.name   Take prefix first, then name, and finally spring application. name
Configure the corresponding DataId spring.cloud.nacos.config.prefix   Take prefix first, then name, and finally spring application. name
Configure content encoding spring.cloud.nacos.config.encode   Read the corresponding encoded content
GROUP spring.cloud.nacos.config.group DEFAULT_GROUP Configure the corresponding group
File extension spring.cloud.nacos.config.fileExtension properties The file extension corresponding to the configuration item. Currently, properties and yaml(yml) are supported
Get configuration timeout spring.cloud.nacos.config.timeout 3000 Timeout for client to get configuration (MS)
Access point spring.cloud.nacos.config.endpoint   The entry domain name of a service in the region. Through this domain name, you can dynamically get the server address
Namespace spring.cloud.nacos.config.namespace   One of the common scenarios is the separation and isolation of configurations in different environments, such as the isolation of resources (such as configuration and service) between development and test environment and production environment
AccessKey spring.cloud.nacos.config.accessKey   When going to alicloud, a cloud account name on alicloud
SecretKey spring.cloud.nacos.config.secretKey   When you want to go to alicloud, you need a cloud account password on alicloud
context path corresponding to Nacos Server spring.cloud.nacos.config.contextPath   context path exposed by Nacos Server
colony spring.cloud.nacos.config.clusterName   Configured as Nacos cluster name
Shared configuration spring.cloud.nacos.config.sharedDataids   DataId of shared configuration, "," split
Share configuration dynamic refresh spring.cloud.nacos.config.refreshableDataids   The DataId that needs to be refreshed dynamically in the sharing configuration is divided into ","
Custom Data Id configuration spring.cloud.nacos.config.extConfig   Attribute is a collection, which is internally composed of ConfigPOJO. Config has three attributes: dataId, group and refresh

7. Nacos Config Actuator Endpoint

Nacos Config internally provides an Endpoint, the corresponding Endpoint ID is Nacos Config, and its actor web Endpoint URI is / Actor / Nacos Config

Note: use Nacos config spring cloud 1 For version x, the URI address is / Nacos config

Among them, the json exposed by Endpoint contains three attributes:

  • NacosConfigProperties: basic configuration information of Nacos currently applied
  • RefreshHistory: configure refresh history
  • Sources: data information of current application configuration

Because the application project generated by aliyun Java initializer activates Spring Boot Actuator Endpoints (JMX and Web) by default, the specific configuration is stored in application In the properties file, at the same time, the actor Web port is set to 8081, as follows:

management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

# Actuator Web access port
management.server.port=8081

Therefore, the application of Nacos config sample needs no adjustment and can be accessed directly: http://127.0.0.1:8081/actuator/nacos-config , the contents of the service response are as follows:

{
  "NacosConfigProperties": {
    "serverAddr": "127.0.0.1:8848",
    "username": "",
    "password": "",
    "encode": null,
    "group": "DEFAULT_GROUP",
    "prefix": null,
    "fileExtension": "properties",
    "timeout": 3000,
    "maxRetry": null,
    "configLongPollTimeout": null,
    "configRetryTime": null,
    "enableRemoteSyncConfig": false,
    "endpoint": null,
    "namespace": null,
    "accessKey": null,
    "secretKey": null,
    "contextPath": null,
    "clusterName": null,
    "name": null,
    "sharedConfigs": null,
    "extensionConfigs": null,
    "refreshEnabled": true,
    "sharedDataids": null,
    "refreshableDataids": null,
    "extConfig": null,
    "configServiceProperties": {
      "secretKey": "",
      "namespace": "",
      "username": "",
      "enableRemoteSyncConfig": "false",
      "configLongPollTimeout": "",
      "configRetryTime": "",
      "encode": "",
      "serverAddr": "127.0.0.1:8848",
      "maxRetry": "",
      "clusterName": "",
      "password": "",
      "accessKey": "",
      "endpoint": ""
    }
  },
  "RefreshHistory": [
    
  ],
  "Sources": [
    {
      "lastSynced": "2020-09-14 11:11:37",
      "dataId": "nacos-config-sample.properties"
    },
    {
      "lastSynced": "2020-09-14 11:11:37",
      "dataId": "nacos-config-sample"
    }
  ]
}

Posted by putraaridana on Sat, 14 May 2022 16:16:47 +0300