Introduction to Nacos installation and use and related principles

1, Nacos installation

Nacos single instance startup command:

startup.cmd -m standalone

At present, the 2.X version of Nacos is somewhat unstable. In the course, the teacher said that he failed to cluster when he tried, but the project couldn't start when he tried on the local machine. Therefore, version 1.3 was used when trying locally. Download address:

https://github.com/alibaba/nacos/releases


Now, you can see whether the configuration file needs to be modified or the default configuration is adopted:

If there is no application.properties file in the conf directory, copy the application.properties.example as application.properties, and change the desired configuration in it.

For details on configuration information, please refer to the following documents: Introduction to Nacos system parameters

Nacos's mind map of personal summary: https://www.processon.com/view/link/61459ef57d9c08198c57a60f

#*************** Spring Boot Related Configurations ***************#
### Default Web context path: the root path of Nacos, which is also the installation path
server.servlet.contextPath=/nacos
### Default web server port: access port
server.port=8847
### If user MySQL as datasource: whether to enable external storage. If you want to use Mysql storage, open it. If not, log out
spring.datasource.platform=mysql
### Count of DB: This is a database related configuration. nacos supports multi data source configuration. Add index to realize the configuration information of different data sources eg: db.url.0
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=10000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=123456
### The ignore urls of auth, is deprecated in 1.2.0: interface skipped by console authentication
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**

After the configuration is completed, enter the bin directory and start startup.cmd. If it is a single instance startup, remember to add the above-mentioned - m standalone. If you are using the default configuration, you can directly access: http://localhost:8848/nacos The account name and password are both Nacos

By default, files are used for data storage, that is, internal storage. If external storage is used, in addition to opening pring.datasource.platform and the following database configurations, the plugins directory (plugins\mysql) and drive need to be added in version 1.x:

2, Use of native Nacos

Create a Meavn project through IDEA and introduce dependencies in the Pom file of the project:

<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-client</artifactId>
    <version>1.1.1</version>
</dependency>

First, we obtain a ConfigService entity according to the address of the registry and the spatial name of the registry. Through the ConfigService entity, we can obtain the configuration information according to the DataID and grouping information. If you want to directly sense the changes in the configuration center on the client, you should configure listening:

public class NacosUtils {
    //Declare related variables in Nacos
    private final static String SERVER_ARR = "127.0.0.1:8847";
    private static HashMap<String,String> NAME_SPACE_IDS = new HashMap();
    private final static Long TIME_OUT = 5000L;
    static {
        NAME_SPACE_IDS.put("public","");
        NAME_SPACE_IDS.put("dev","2345sate");
    }

    //Simple query of configuration center information
    static String getConfig(String spaceName,String groupName,String dataId) throws Exception {
        //Parameter validity detection
        if (!checkDatas(dataId))throw new Exception("DataId It's empty. Check the wool data");
        //Get ConfigService
        ConfigService configService = getConfigService(spaceName);
        //Get configuration information
        return configService.getConfig(dataId, groupName, TIME_OUT);
    }
    static String getConfig(String groupName,String dataId) throws Exception{
        return getConfig(null,groupName,dataId);
    }
    static String getConfig(String dataId) throws Exception{
        return getConfig(null,"DEFAULT_GROUP",dataId);
    }

    //Monitor the reading of the configuration center
    static void getConfigByListener(String spaceName,String groupName,String dataId) throws Exception {
        final int[] changeCount = {0};
        if(!checkDatas(dataId))new Exception("DataId It's empty. Check the wool data");
        ConfigService configService = getConfigService(spaceName);
        //Add listening events to configService
        System.out.println("***The program starts listening for events in the configuration center***");
        configService.addListener(dataId, groupName, new Listener() {
            public Executor getExecutor() {
                return null;
            }

            public void receiveConfigInfo(String s) {
                changeCount[0]++;
                System.out.println("~~~A second error occurred in the configuration data"+ changeCount[0] +"modify~~~");
                System.out.println(s);
            }
        });
        while (changeCount[0] <5){
            Thread.sleep(100L);
        }
    }
    static void getConfigByListener(String groupName,String dataId) throws Exception {
        getConfigByListener(null,groupName,dataId);
    }
    static void getConfigByListener(String dataId) throws Exception {
        getConfigByListener(null,"DEFAULT_GROUP",dataId);
    }
    //Get ConfigService according to configuration
    static ConfigService getConfigService(String spaceName) throws Exception {
        //Get ConfigService
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR,SERVER_ARR);
        if (spaceName!=null){
            String nameSpaceId = NAME_SPACE_IDS.get(spaceName);
            if (nameSpaceId==null){
                throw new Exception("spaceName Non compliant, no corresponding id");
            }
            properties.put(PropertyKeyConst.NAMESPACE,nameSpaceId);
        }
        return ConfigFactory.createConfigService(properties);
    }
    //Check the legitimacy of incoming data
    static boolean checkDatas(String dataId){
       return dataId==null||dataId==""?false:true;
    }
}

The result of this method is:

3, Integrating spring cloud

By integrating spring cloud, we can easily use Nacos in the project. For example, we can simplify related configuration and other operations. First, configure the Pom file:

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.9</version>
    </dependency>
</dependencies>

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

When configuring the information related to the configuration center, make sure to load it first, so we configure the information related to the configuration center to bootstrap.yml:

server:
  port: 9001
spring:
  application:
    name: config1
  cloud:
    nacos:
      config:
        #127.0.0.1:8860
        #This configuration method has the highest configuration priority
        server-addr: 127.0.0.1:8860,127.0.0.1:8861,127.0.0.1:8862
        file-extension: yaml
        namespace: 2345sate
        group: DEFAULT_GROUP
        #Multiple data source configuration mode 1: it ranks second in terms of configuration priority
        ext-config[0]:
          data-id: config2.yaml
        ext-config[1]:
          data-id: config3.yaml
          group: LML_GROUP
        ext-config[2]:
          data-id: config4.yaml
          group: LML_GROUP
          refresh: true
        #Multi data source configuration mode 2: this paradigm configuration is convenient, but it is only applicable to them belonging to the same group;
        #It is also at the end of the priority of configuration
        #shared-dataids: config2.yaml,config3.yaml,config4.yaml
        #refreshable-dataids: config3.yaml

In the configuration mode with the highest priority, he will p r e f i x − {prefix}- The rules of prefix − {spring.profiles.active}. ${file extension} (spring.profiles.active is the profile corresponding to the current environment) generate the final dataid to match in the configuration center. Therefore, during configuration, pay attention to that the final generated dataid corresponds to that in the configuration center, otherwise it will not be found, Just like the above, the final dataid is config1.yaml, which requires that our configuration center must have a corresponding:

The configuration of multi data source related configurations in the bootstrap file is relatively simple. Different addresses are separated by "," and. The configuration of nacos cluster is mainly realized through the configuration file under nacos config, which mainly modifies the port, local address, cluster configuration and other information

127.0.0.1:8860
127.0.0.1:8861
127.0.0.1:8862

This is the cluster related configuration file. Then we change the following in application.properties:

There are two problems encountered during the actual operation of the local machine. One is that the service started directly through startup.cmd is a single instance, rather than the default cluster. The phenomenon is that each machine in the cluster is up, but there are no other nodes in the cluster management. This should be related to the contents of the CMD file. In the CMD file, the cluster mode is declared:

After this problem is solved, it can be started, but it will still report errors. Each node reports errors, which is at the database level. At this time, I will talk about the release of mysql related configuration. When the three Nacos nodes are connected to a library, it can be started successfully. When they are connected to a library respectively, the cluster can be built successfully. My personal guess is that this is not to say that external storage must be configured for cluster startup, but may be related to our plugins plug-in. Of course, this is only speculation.

The test code of the final program is:

@RefreshScope
@RestController
public class NacosServerController {
    @Resource
    private ConfigurableApplicationContext configurableApplicationContext;

    @Value("${student.age:No corresponding value found}")
    private String config1Name;

    @Value("${config2.name:config2 No value}")
    private String config2Name;

    //When @ RefreshScope directly passes through @ Value without annotation, it will not perceive the change of configuration center
    @GetMapping("/getNameNoFresh")
    public String getNameNoFresh(){
        return config1Name+"  "+config2Name;
    }

    //Perceive the changes of configuration center data through getEnvironment
    @RequestMapping("/getNameFresh")
    public String getNameFresh(){
        String name1 = configurableApplicationContext.getEnvironment().getProperty("config2.name");
        return name1+"~~~~~~~~~~~";
    }
    //When @ RefreshScope is added, it will be refreshed automatically
}

Among them, we should pay attention to the two methods of data change monitoring and how to get the value in the configuration file

4, Temporary and permanent nodes

(8 messages) nacos temporary instance and persistent instance_ Jak's blog - CSDN blog_ nacos temporary and permanent instances

Temporary nodes and permanent nodes are determined by different health check modes. Node health check modes can be divided into agent and server modes:

  • agent reporting mode

    The client reports the status to the server through heartbeat. If the status is not reported for more than 15 seconds, it will be marked as unhealthy. If it is not reported for more than 30 seconds, this node will be deleted. The node in this detection mode is a temporary node, that is, a temporary instance

  • Server active detection

    The nacos server actively detects the node's status every 20 seconds. If the health detection fails, it will be marked as unhealthy but will not be deleted. The method of setting a temporary instance is as follows:

    # Default false
    spring:
    	cloud:
    		nacos:
    			discovery:
    				ephemeral: true
    

The registered instance supports the ephemeral field

In version 1.0.0 of Nacos, an emphemeral field is added in the instance level to set temporary nodes and permanent nodes. The appearance of this setting indicates that there may be two nodes in a service center at the same time. true is the agent mode in health detection and false is the server mode in health detection.

Setting of Server running mode

At present, Nacos Server supports three operation modes: AP, CP and MIXED. The concepts of CP and AP are due to the concept of CAP. You can see the introduction on my Dubbo related blog:

CP: consistency, partition fault tolerance

AP: availability, partition fault tolerance

MIXED: this mode is mainly set up to support both temporary instances and persistent instances. In this mode, a service must be created before registering an instance. On the premise that the service already exists, temporary instances can be registered in the case of network partition

Difference between temporary instance and permanent instance

Temporary instances are more suitable for those services that need to cope with the sudden increase of traffic and elastic capacity expansion. When the traffic drops, these instances can be destroyed by themselves without processing in Nacos. However, the health status can be seen in real time during persistence, which is convenient for subsequent warning, capacity expansion and other processing.

Switching between CA and CP:

Nacos cluster supports the AP principle in the CAP principle by default, but it can also be switched to the CP principle. The switching commands are as follows:

curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP'

Meanwhile, the bootstrap.properties of the microservice should be configured with the following options to indicate that it is registered as a temporary / permanent instance. AP mode does not support data consistency, so only temporary instances of service registration are supported. CP mode supports permanent instances of service registration to meet the consistency of configuration files:

#false is a permanent instance, and true indicates that the temporary instance is open and registered as a temporary instance
spring.cloud.nacos.discovery.ephemeral=false

5, CMDB mechanism

How to get through CMDB and visit nearby - Alibaba cloud yunqi - blog Park (cnblogs.com)

How to get through CMDB and visit nearby - alicloud developer community (aliyun.com)

In enterprises, CMDB is generally used to store metadata information related to machines, equipment, services and applications. We can access the same machine room through CMDB. As for why to realize the same computer room access, this is because a request will also have a longer delay due to the regional distance. eg: Generally speaking, if the request and service are in the same city, their corresponding time is generally 1ms, but if the two are separated by Beijing and Shanghai, the requested delay may be 30ms.

In Nacos, there are two ways to obtain CMDB information, one is through the information stored locally, and the other is through the information of the third-party system. As for how to connect with the third-party system Nacos, the SPI strategy is adopted. After the implementation, turn on the relevant switches in the configuration file:

nacos.cmdb.loadDataAtStart=true

At this time, we will get the information of the third-party CMDB. With this information, we can use the Selector to achieve priority access to the same computer room. In fact, CMDB is also a load balancing strategy to realize the nearest access to.

A problem here is that Nacos returns the access list to the client. In other words, when the Nacos client connects to the Server, is this load balancing implemented on the client?

6, Environmental isolation

https://nacos.io/zh-cn/blog/address-server.html

There are many different environments in the real project scenario. How to realize the isolation between environments is a problem that needs to be considered. Generally, the isolation we say can include logical isolation and physical isolation.

1. Some advantages of environmental isolation

  • Fault isolation

When we use physical isolation, a system is an independent business processing unit, which contains all business processing logic, and any request of a user will be completed in this unit. At this time, if we cut the request into 10 business units for processing according to the id, only 1 / 10 of the processing units have abnormal effects, which can greatly improve the overall availability of the system.

  • Fault recovery

When a system fails, you can switch the route requested by the system to another system through rapid distribution configuration, which greatly speeds up the recovery of the system. Not only the isolation between environments, but also the configuration distribution of the configuration center. Although I can understand it, I still can't understand how to implement a routing replacement and its design principle.

  • Gray scale test

The environment isolation function ensures that requests are processed in the specified machine cluster. No configuration is required for development and testing, which greatly improves the R & D efficiency. In the original words, you may need to test the notification, do a lot of host binding, configure JVM parameters, etc.

2. Two ways to initialize the Nacos client instance

  • Directly tell the client the IP address of the nacos server
  • Tell the client an endpoint. The client queries the nacos server IP list at the endpoint through HTTP request

Configure the mapping relationship between the network segment and the environment at the endpoint. After receiving the client's request, the endpoint calculates the client's environment according to the network segment to which the client's source IP belongs, and then finds the IP list of the corresponding environment and returns it to the client.

Nacos uses network segments to isolate the environment. If we want to do so, we must have several preconditions: the applications deployed by a machine are in the same environment, which can ensure that we can calculate the corresponding environment of the machine according to the IP address at the endPoint. Then the second necessary condition arises. We should be able to detect the IP address of the client; At the same time, we should also ensure that only one environment Nacos can be connected in a process by default, so that the Nacos to be connected will not be blocked by endPoint; Finally, since we use the network segment for environmental isolation, we must plan the network segment of the machine, otherwise the irregular network use will not wake up a series of governance by using the network segment

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-h00mqmjr-1632236494486) (F: \ typroa \ images \ image-20210918165028153. PNG)]

3. Implementation of address server

Based on nginx implementation, the geo module of nginx is used to map the IP side and the environment, and then nginx is used to return the static file content. This part requires a certain reserve of nginx related knowledge, which will be explored later.
Environment isolation. If we want to do this, we must have several preconditions: the applications deployed by a machine are all in the same environment, which can ensure that we can calculate the corresponding environment of the machine according to the IP address at the endPoint, so the second necessary condition is born. We should be able to detect the IP address of the client; At the same time, we should also ensure that only one environment Nacos can be connected in a process by default, so that the Nacos to be connected will not be blocked by endPoint; Finally, since we use the network segment for environmental isolation, we must plan the network segment of the machine, otherwise the irregular network use will not wake up a series of governance by using the network segment

3. Implementation of address server

Based on nginx implementation, the geo module of nginx is used to map the IP side and the environment, and then nginx is used to return the static file content. This part requires a certain reserve of nginx related knowledge, which will be explored later.

Posted on Tue, 21 Sep 2021 13:14:51 -0400 by sturbitt