In the last article, we introduced the service’s use of NACOS as a registry. In fact, NACOS also serves as a configuration center, but it is much more powerful and easy to configure than SpringCloud-Config. The configuration file is pretty well understood. We often use properties to configure various content in our projects. For example, we configure urls that call other services into a configuration file. However, in a distributed architecture ecosystem, each application has to maintain its own configuration. First, the dynamic update of the configuration, second, the same configuration needs to be modified several times, and third, the security problem. Therefore, we generally maintain a configuration center in the micro-service system to dynamically change the configuration and dynamically push the changed content to the corresponding service node. Achieve the effect of hot update. So the configuration center is also an important component under the microservices system.

Nacos is introduced as the configuration center

We now have many open source components as configuration centers, such as ZooKeeper, Apollo, Spring Cloud Config, and so on. Whatever the component ends up doing is the same. Nacos as a service discovery function has been introduced in the last article. In the last article, we said that another core function of NACOS is as a configuration center, which can add, delete, modify and check the configuration content and realize hot change of content configuration. Next, let’s introduce how to implement the nacos Config function.

Nacos implements config function configuration

  • Enter the control page of Nacos. In the configuration list function page, click the “+” button in the upper right corner to enter the “New Configuration” page. Fill in the content as shown below:

The above configuration is briefly explained:

  1. Data ID: task – gray
  2. Group: Do not change the default value DEFAULT_GROUP
  3. Configuration format: We usually choose YAML or Properties or JSON
  4. Configuration content: The configuration content to be loaded by the application. This section is used as an example only

You can also change the configuration through the REST interface, or log in to the GUI to edit and publish the configuration.

curl -X "POST" "http://127.0.0.1:8848/nacos/v1/cs/configs" \
     -H 'Content-Type: application/x-www-form-urlencoded; charset=utf-8' \
     --data-urlencode "dataId=nacos.properties" \
     --data-urlencode "group=DEFAULT_GROUP" \
     --data-urlencode "content=useLocalCache=true
Copy the code
  • Used in projects
  1. Create a Spring Boot application that you can name alibaba-nacos-config. Pom file:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0. 5.RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR1</version> <type>pom</type> <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>0.22..RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.182.</version>
        <optional>true</optional>
    </dependency>
</dependencies>
Copy the code

As you can see from the previous article, the nacOS registry module is not included in this example, so the two content can be used independently.

  • Create the application main class and implement a Controller interface:
@SpringBootApplication
public class TestApplication {

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

    @Slf4j
    @RestController
    @RefreshScope
    static class TestController {

        @Value("${gray-city}")
        private String city;

        @GetMapping("/test")
        public String hello(a) {
            returncity; }}}Copy the code
  • Create the configuration file bootstrap.properties and configure the service name and Nacos address
spring.application.name=alibaba-nacos-config
server.port=8001
spring.cloud.nacos.config.server-addr=127.0. 01.:8848
Copy the code

Note: You must use bootstrap.properties here. Also, the spring.application.name value must match the configuration Data Id created in the previous phase of Nacos (except for.properties or.yaml suffixes).

  • Start the application created above
2021-01-27 18:29:43.497  INFO 93597 --- [main] o.s.c.a.n.c.NacosPropertySourceBuilder   : Loading nacos data, dataId: 'alibaba-nacos-config.properties', group: 'DEFAULT_GROUP'
2021-01-27 18:29:43.498  INFO 93597 --- [main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='alibaba-nacos-config.properties'}}]Copy the code
  • Verify configuration fetch and verify dynamic refresh

Using curl or postman, access the interface: localhost:8001/test. If all is well, the configuration in Nacos will be returned. Then, through the Nacos page, modify the content, click publish, then access the interface, and you can see that the return results have changed. At the same time, we can also see the following logs on the application client:

2021-01-27 18:39:14.162  INFO 93597[-127.0. 01 _8848.] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [gray-city]
Copy the code

Nacos configuration rules detailed

The configuration content created in Nacos looks like this:

  • Data ID: alibaba – nacos – config. Properties
  • Group: DEFAULT_GROUP

There are three elements, which correspond to the configuration content of the specific application as follows:

  • Alibaba-nacos-config in Data ID: the configuration corresponding to the client is actually the service name
  • Spring. Cloud. Nacos. Config. The prefix, the default value is ${spring. Application. The name}, i.e., the service name
  • The properties of the Data ID: spring. The corresponding client configuration cloud. Nacos. Config. The file – the extension, the default values for the properties
  • Group, the value of the DEFAULT_GROUP: spring. The corresponding client configuration cloud. Nacos. Config. The Group, the default value is DEFAULT_GROUP

Data ID=${spring.application.name}. Properties, Group=DEFAULT_GROUP.

  1. If we want to load content in yamL format instead of Properties format, we can load Data ID=alibaba-nacos-config.yaml, Group=DEFAULT_GROUP by configuring it as follows.
  2. If we do Group management for the configuration, we can load Data ID=alibaba-nacos-config.yaml, Group=TEST_GROUP

For spring. Cloud. Nacos. Config. Group configuration, and use it to distinguish between different USES the configuration of the content, or use it to distinguish different environment configuration. For detailed configuration details, see the configuration example on the official website. Namespace description: If the same Group or Data ID exists. One of the common scenarios of Namespace is the isolation of different environment configurations, for example, the isolation of resources (such as configurations and services) between the development and test environment and production environment.

  • First, in Nacos, create multiple namespaces based on the environment name.
  • At the top of the configuration list, you can see that in addition to Public, there are several namepsaces you just created. Create the configuration content for the alibaba-nacos-config application in the DEV and TEST Spaces respectively.

  • In alibaba – nacos – config application configuration file, add the Namespace specified configuration, such as: spring. Cloud. Nacos. Config. The Namespace = unique identification of the above. (Note that the namespace configuration uses the NAMESPACE ID instead of the name.) The official recommendation is to use namespaces to distinguish different environments, freeing the freedom of groups. In this way, groups can be used to focus on Group management at the business level.

Multi-file loading of Nacos configuration. The mapping of configuration contents in Nacos is controlled by the following three parameters:

  • spring.cloud.nacos.config.prefix
  • spring.cloud.nacos.config.file-extension
  • spring.cloud.nacos.config.group

By default, the configuration with Data ID=${spring.application.name}. Properties, Group=DEFAULT_GROUP is loaded. Data ID= a.perties, Group=DEFAULT_GROUP and Data ID= B.perties, Group=DEFAULT_GROUP are created in Nacos. In the Spring after Cloud applications through the use of the Spring. The Cloud. Nacos. Config. Ext – config parameters configuration is to be loaded to the content of the two configurations:

spring.cloud.nacos.config.ext-config[0].data-id=a.properties
spring.cloud.nacos.config.ext-config[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.ext-config[0].refresh=true
spring.cloud.nacos.config.ext-config[1].data-id=b.properties
spring.cloud.nacos.config.ext-config[1].group=DEFAULT_GROUP
spring.cloud.nacos.config.ext-config[1].refresh=true
Copy the code

Spring. Cloud. Nacos. Config. Ext – config configuration is an array type List. Each configuration contains three parameters: data-id, group, and refresh.

Nacos data persistence

Nacos single machine running mode is only suitable for learning and testing environment. It is obviously not suitable for production environment with high availability requirements. Therefore, we must have a persistence scheme for Nacos data. By default, Nacos uses an embedded database for data storage. Therefore, if you start more than one Nacos node in the default configuration, the data store is inconsistent. To solve this problem, Nacos has adopted a centralized storage approach to support clustered deployment, currently only MySQL storage is supported.

  1. Installing the database
  2. To initialize the MySQL database, the database initialization file is nacos-mysql.sql, which is available in the conf directory under the nacos package
  3. Modify the conf/application. The properties files, increase support for MySQL data source configuration, add (currently only supports MySQL) data source url, user name and password

Nacos data consistency algorithm raft algorithm, we will introduce in future articles.

Nacos cluster deployment

In the Nacos conf directory, there is a cluster.conf.example file. You can use it without the example extension, or you can create a separate cluster.conf file and open it. This article takes the example of starting three Nacos servers at different local endpoints, which can be configured as follows:

127.0. 01.:8841
127.0. 01.:8842
127.0. 01.:8843
Copy the code

With the above configuration complete, we are ready to start Nacos instances on each node to build a Nacos cluster for use.

Production deployment

In the actual production environment, because each instance is distributed on different nodes, you only need to run the sh startup.sh command in the Nacos bin directory of each node. In addition, we need to create an access point for the three Nacos instances that we start that can be load-balanced for them. There are many ways to do this, and we can use Nginx to do reverse proxy load balancing on the next three nodes, i.e. VIP in the figure above. Then we can configure the proxy address via Nginx: http://localhost:8080/nacos/ to access the Nacos, In the Spring Cloud applications can also use this address to access the address as the center of the registry and configuration to configure (can also be Spring. Cloud. Nacos. Config. Server – addr = 127.0.0.1:8841127.00 0.1:8842, 127.0.0.1:8843). To learn more about microservices, please visit our official account: IT Technology Stack. To find out more.