preface

Nacos is the service registry and configuration center of Alibaba open source, and is committed to providing developers with a convenient and easy to use open source framework.

What’s so amazing about Nacos? See below:

It is not hard to see Alibaba’s ambition from the above figure. One Nacos has eliminated the three components of Spring Cloud, namely registry Eureka, service configuration Config and service Bus.

The directory structure of this paper is as follows:

Why is Nacos so popular?

The introduction to the official Nacos documentation includes the following sentence:

Nacos helps you build, deliver, and manage microservices platforms more agile and easily. Nacos is the service infrastructure for building modern “service” centric application architectures (e.g., microservices paradigm, cloud native paradigm).

What does that mean? Don’t worry, there is contrast to hurt.

I believe you have all used Eureka and Config. How do you feel?

Of course, these two components give me the most intuitive feeling is tedious, for the following reasons:

  1. Both Eureka and Config have to build their own services
  2. The English interface is not very friendly

Developers who have used Nacos say it’s great. Instead of building your own service, Alibaba has prepared the service for you. You just need to start it. The interface is available in Both Chinese and English, suitable for beginners.

The most important reason, of course, is that the above components are likely to stop working. Eureka has already stopped working, and who knows what other components will do the same?

How to teach yourself?

For starters, the official documentation for Nacos is listed below:

  • Nacos. IO/useful – cn/docs /…
  • Spring – the cloud – alibaba – group. Making. IO/lot – page…
  • Github.com/alibaba/nac…

Version Description

Maven-based microservice projects are built with the following component versions:

  • JDK1.8 +
  • Spring the Boot – 2.2.2. RELEASE
  • SpringCloud-Hoxton.SR3
  • SpringCloud Alibaba – 2.2.1. RELEASE

Note: The Spring Boot, Spring Cloud, Spring Cloud Alibaba versions are not selected randomly, the official website specifies the adaptation of each version: github.com/alibaba/spr…

Different versions of Alibaba also correspond to different component versions, as shown below:

Be sure to choose the version given in full accordance with the document, otherwise unexpected bugs will appear, it is not chicken chicken….

The author uses a modular aggregate project demo with dependencyManagement as follows, corresponding to the version mentioned above:

Note: if your version is not the same as the author’s, please be sure to strictly follow the official document to the version adaptation, otherwise there will be unexpected bugs….

Start the Nacos service

According to the Spring Cloud Alibaba version selected by the author above, the corresponding Nacos version is 1.2.1, go directly to GitHub(github.com/alibaba/nac…

After downloading it, you can unzip it. From its directory structure and file name, this is a Spring Boot project.

Go to the /bin directory and there are two scripts as follows:

  • startup.cmd: Startup script for Windows
  • startup.sh: Startup script for Linux

If the author runs Windows, double-click startup. CMD to start the project. If the following interface is displayed, the startup is complete:

In the browser type http://localhost:8848/nacos into Nacos login interface.

User name: nacos; Password: nacos

The successful login page is as follows:

Service Registration Discovery

It is believed that all of us have used Eureka for service registration and discovery of micro-services, so we need to build a Eureka micro-service locally. However, the integration of Alibaba’s Nacos is not so complicated, so we can directly start the Nacos service provided by Alibaba, so that programmers can focus all their energy on business. Here is a simple architecture diagram:

How do you demonstrate that?

Referring to the above architecture diagram, the author created two modules respectively, namely, NACOS-Provider (service provider) and NACOS-Consumer (service consumer), with the following responsibilities:

  • nacos-provider: Register into NACOS-server and expose the service externally
  • nacos-consumerRegister with nacOS-server and invoke the nacOS-provider service

The nacos-Provider service provider is created

Because of the multi-module aggregation project, you only need to create a NACOS-Provider module. The steps are as follows:

1. Add Maven dependencies

The dependency spring-cloud-starter-alibaba-nacos-discovery needs to be added, as shown below:

Since the version of spring-cloud-alibaba-dependencies is specified in the parent template, it is not necessary to specify the version number in the sub-module to achieve version management effect.

2. Configure the YML file

Specify the service name, port number, nacOS-server address and other information in the configuration file as follows:

Server: port: 9001 Spring: Application: ## Server-addr: 127.0.0.1:8848 Management: endpoints: web: exposure: ## yML file contains special characters that must be included in single quotation marks.Copy the code

3. Enable the service registration discovery function

The @enableXXXX annotation is required to enable a function for most Spring Boot function modules. Otherwise, automatic configuration cannot be introduced. Here, the native annotation @enableDiscoveryClient of Spring Cloud is required to enable the service registration discovery function, as follows:

Write a demo service

Nacos-provider is registered with nacOS as a service provider. It must provide a service to be invoked by nacOS-consumers. The following interface is written arbitrarily:

5. Start the project

Following the five steps above completes the basic service. Now you just need to start the nacos-Provider service.

After successful startup, you will find the registered service nacOS-Provider in the service Management -> Service List of NACOS, as shown in the following figure:

OK, you can see in nacOS that the service was successfully registered, complete the task……….

Nacos-consumer service consumer creation

It is also registration to enter NACOS, so the general steps are the same, as follows:

1. Add Maven dependencies

The dependency spring-cloud-starter-alibaba-nacos-discovery needs to be added, as shown below:

2. Configure the YML file

Specify the service name, port, and nacos-server address as follows:

server:
  port: 9002
spring:
  application:
    name: nacos-consumer
  cloud:
    nacos:
      discovery:
        # nacos service address
        server-addr: 127.0. 01.: 8848
management:
  endpoints:
    web:
      exposure:
        Special characters exist in the ## yML file and must be enclosed in single quotation marks; otherwise, an error will be reported during startup
        include: The '*'
Copy the code

3. Enable the service registration discovery function

Annotated with @enableDiscoveryClient, as shown below:

Write a demo service

How do you demonstrate that? Nacos-provider provides a service, so let’s invoke its service to demonstrate this.

Nacos is integrated with the Ribbon. Why? The dependency of Spring-cloud-starter-Alibaba-nacos-discovery can be seen as follows:

So we can use the Ribbon’s load balancing to invoke services as follows:

  • To create the RestTemplate, use the@LoadBalancedAnnotation Enable load balancing as shown in the following figure:

  • The service is invoked directly using the service name registered with NACOS as the access address, as shown below:

  • In the picture aboveserviceUrlWhat is it? Is it an IP address? Of course not, since both nacOS-provider and NACOS-consumer are registered with NacOS, it is possible to find the appropriate service directly by service name, so thisserviceUrl=http://service-name, as shown below:

OK, now that nacos-Consumer is ready, you can start the project.

5. Start the project

After successful startup, two services will be displayed in the service list of NACOS, namely, NACOS-Provider and NACOS-Consumer, as shown below:

At this point both the service provider and the consumer have successfully registered with Nacos, and it is now a matter of testing whether the service can be tuned.

Direct call nacos – consumer interface, enter the address: http://localhost:9002/nacos/test/16, return to the information shown in the following drawings to call one another success:

conclusion

Nacos found it easy to register services, much easier than Eureka, without having to build your own registry.

Start Configuration Management

Why configuration Management? In fact, this is not only the pain point of micro services, individual services also exist such a pain point. Should an online project stop updating if it wants to change a configuration, such as adding a data source? Obviously not realistic, so how to solve?

I’ve already written an article about singleton applications. If you’re interested, see: How to make Spring Boot configuration “live”?

There are many options in the microservice environment, such as Config+BUS and Ctrip’s open source Apollo….

This is not the focus of today, how do you feel after using Config+BUS? Do you feel uncomfortable when you have to build a Config microservice and integrate GitHub?

Here’s how Nacos does configuration management and dynamic refreshing perfectly.

How do you demonstrate that?

A new module nacOS-config is created to integrate NACOS to realize configuration management. The project structure is as follows:

Where can I see the list of Nacos configurations? In the management Platform -> Configuration Management -> Configuration List column, as shown below:

Add the dependent

Because of the module aggregation project, there is no need to specify a version number, depending on the following:

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

Configure the YAML file

In the bootstrap.yml file, set the Nacos configuration as follows:

spring:
  application:
    name: nacos-config
    -> ${prefix}-${spring.profiles. Active}.${file-extension} -> ${prefix}-${spring.profiles. Active}.
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        ## address of nacOS as the configuration center
        server-addr: 127.0. 01.: 8848
        -> ${prefix}-${spring.profiles. Active}.${file-extension} -> ${prefix}-${spring.profiles. Active}.
        file-extension: properties
management:
  endpoints:
    web:
      exposure:
        Special characters exist in the ## yML file and must be enclosed in single quotation marks; otherwise, an error will be reported during startup
        include: The '*'
Copy the code

What is a Data ID?

DataId is the unique identifier of a configuration. The format is as follows:

${prefix}-${spring.profiles.active}.${file-extension}
Copy the code
  • prefix: prefix, the default isspring.application.nameIs also available through the configuration itemspring.cloud.nacos.config.prefixTo configure.
  • spring.profiles.active: indicates the profile of the current environment. whenspring.profiles.activeIf null, the corresponding concatenate-Also will not exist, the dataId splicing format becomes${prefix}.${file-extension}
  • file-exetensionFor the data format of the configuration content, you can pass the configuration itemspring.cloud.nacos.config.file-extensionTo configure. Currently only supportedpropertiesyamlType.

Adding a Configuration

Add a config.version configuration to nacOS as shown below:

This is the configuration of the added config.version. After the release, check the list as shown below:

Get the configuration in NACOS

Getting the configuration in NACOS is as simple as reading it directly using the native @value () annotation as follows:

  • Create a new entity classDynamicConfigEntity:
@Component
@Data
public class DynamicConfigEntity {

    // Read the config. Version configuration directly from nacOS
    @Value("${config.version}")
    private String version;
}
Copy the code
  • Create a new Controller test as follows:
@RestController
@RequestMapping("/nacos")
public class NacosController {

    @Autowired
    private DynamicConfigEntity entity;


    @GetMapping("/test/{id}")
    public String test(@PathVariable("id")Integer id){
        return "accept one msg id="+id+"----- version="+entity.getVersion(); }}Copy the code

Run after the success of the project, the browser input address: http://localhost:9003/nacos/test/1, returned the following results:

The result is clearly that the configuration in Nacos works. Isn’t that easy?

How do configurations refresh dynamically?

Imagine: Now that the requirements have changed and I need to change the config.version configuration to 2, will it work if I change the configuration in Nacos directly?

Try this by changing the configuration in Nacos directly to 2, as shown below:

At this point we don’t restart the project under the condition of visit: http://localhost:9003/nacos/test/1, the results are as follows:

What??? Why hasn’t it changed? Didn’t Nacos automatically refresh the configuration?

Nacos also requires the @refreshScope annotation to automatically refresh the configuration. The annotation is also used in Config, and is marked on the entity class of the configuration as follows:

@Component
@RefreshScope
@Data
public class DynamicConfigEntity {

    // Read the config. Version configuration directly from nacOS
    @Value("${config.version}")
    private String version;
}
Copy the code

Now add @ RefreshScope restart will Nacos config. The version of this configuration change to 3, then go to http://localhost:9003/nacos/test/1, the results are as follows:

How do multiple environments isolate configurations? (Namespace)

Consider this: Normal business development has at least three environments, as follows:

  • Dev: local development environment
  • Test: indicates the test environment
  • Prod: production environment

The configuration of each environment must be different, so how can the three different configurations be clearly distinguished in Nacos?

Many people may ask: Isn’t there an environment distinction in the DataId format? Isn’t that enough?

DataId can certainly tell the difference, but isn’t there more to microservice configurations? How do you find it once you have more? A mix of environments. Can you tell?

Of course, Alibaba’s Nacos development team has clearly taken this issue into account, and namespace is officially recommended to solve the problem of environment configuration isolation.

Namespace: Addresses data isolation in multiple environments and tenants. You can create namespaces based on specific environments to isolate data in multiple environments

Nacos provides the public namespace by default. The config. Version configuration above belongs to the public namespace, as shown in the following figure:

Of course, we can create our own namespace according to business needs, as shown in the following figure:

Chen created three, namely dev, test and Prod, as shown below:

Note: The Namespace ID in the figure above is a unique ID automatically generated by the system. This ID will be used to specify different namespaces later.

Once created, different namespaces can be seen above the configuration list, as shown below:

Now that Namespace is configured in Nacos, what about microservices? As mentioned earlier, Nacos specifies a public namespace by default, so how do you specify a namespace in a project?

If you add config.version=4 to the test namespace, as shown below:

In this case, you only need to specify the following configuration in the bootstrap.yml configuration:

spring:
  application:
    name: nacos-config
  cloud:
    nacos:
      config:
      The namespace ID is the test namespace ID
        namespace: d0ffeec2-3deb-4540-9664-fdd77461fd6b
Copy the code

Note: Namespace must be specified in the bootstrap.yml configuration file, otherwise it does not take effect.

So far, already all configured, start the project, the browser to http://localhost:9003/nacos/test/1, the results are as follows:

How can DIFFERENT service configurations be isolated? (Group)

Imagine a scenario where you have two microservices, an order system and a user system, but they have the same configuration, such as datasource-URL. How do you tell the difference?

In this case, Group comes in handy. As the name implies, Group means grouping.

Group: A set of configuration sets in Nacos, which is one of the dimensions of organizational configuration. In simple terms, the configuration files of different systems or microservices can be placed in a Group. Nacos If the Group is not specified, the default Group is DEFAULT_GROUP.

In the above scenario, the order system and user system can be divided into separate groups, such as ORDER_GROUP and USER_GROUP. Of course, this is a relatively fine-grained grouping. According to the business of the enterprise, multiple microservices can also be grouped into a group.

Create a config. Version =5 in Nacos with namespace test and group ORDER_GROUP, as shown below:

The configuration of namespace test is as follows:

In the bootstrap.yml configuration file, specify groups as follows:

spring:
  application:
    name: nacos-config
  cloud:
    nacos:
      config:
        ## Specifies the namespace
        namespace: d0ffeec2-3deb-4540-9664-fdd77461fd6b
        ## Specify the group as ORDER_GROUP
        group: ORDER_GROUP
Copy the code

Note: The Group configuration is configured in the bootstrap.yml file, just like Namespace.

So far, already all configured, start the project, the browser to http://localhost:9003/nacos/test/1, the results are as follows:

conclusion

Configuration management and dynamic configuration refreshes are easy to implement in Nacos, summarized as follows:

  1. Add the correspondingspring-cloud-starter-alibaba-nacos-configRely on
  2. Using native annotations@Value()Import the configuration
  3. Using native annotations@RefreshScopeRefresh the configuration
  4. Isolate multiple environment configurations (Namespace) and different service configurations (Group) based on your own service scenarios
  5. Remember: namespace and grouping configuration must be inbootstrap.ymlorbootstrap.propertiesIn the configuration file

How does Nacos share configuration?

Scenario: As the number of microservices in a project gradually increases, there will inevitably be the same configuration, so we can extract the same configuration as the common configuration of the project, such as data source information in the cluster..

The shared configuration of Nacos solves this problem perfectly, and is simple to configure, but powerful.

Create a share configuration in Nacos

Share-config1. properties (share-config2.properties)

Note: DataId must have the suffix “properties” or “yML”

The configuration of share-config1.properties is as follows:

database.url=JDBC: mysql: / / 112.111.0.135:3306 / nacos_config? characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
Copy the code

The configuration of share-config2.properties is as follows:

database.user=root
Copy the code

Create a new module nacos-config-share

Create a new module nacos-config-share to demonstrate the effect, relying on the same nacos-config

The bootstrap.yml configuration is as follows:

spring:
  application:
    name: nacos-config-share
  cloud:
    nacos:
      config:
        ## Specifies the namespace
        namespace: 51f0479b-a88d-4646-902b-f2a063801502
        ## address of nacOS as the configuration center
        server-addr: 127.0. 01.: 8848
        -> ${prefix}-${spring.profiles. Active}.${file-extension} -> ${prefix}-${spring.profiles. Active}.
        file-extension: properties
management:
  endpoints:
    web:
      exposure:
        Special characters exist in the ## yML file and must be enclosed in single quotation marks; otherwise, an error will be reported during startup
        include: The '*'
Copy the code

The above configuration is similar to nacos-config, specifying application.name, namespace, file-extension, and nacos service address….

Of course, in addition to the above configuration is certainly not enough, to share the configuration also need to add the following configuration:

spring:
  application:
    name: nacos-config-share
  cloud:
    nacos:
      config:
        ## Shared configuration, List collection, can be configured multiple
        shared-configs:
          ## dataId: The dataId of the configuration file, which must have a suffix
          - dataId: share-config1.properties
          ## refresh: Specifies whether to refresh dynamically. The default is false
            refresh: true
          - dataId: share-config2.properties
          ## Specifies the grouping of configuration files. The default is DEFAULT_GROUP
            group: ORDER_GROUP
            refresh: true
Copy the code

To see the effect, you must import the configuration via @value (), as follows:

@Component
@RefreshScope
@Data
public class DynamicConfigEntity {
    // Get database.url from the share configuration file
    @Value("${database.url}")
    private String databaseUrl;

    // Get database.user from the share configuration file
    @Value("${database.user}")
    private String user;
}
Copy the code

Configured above, start nacos – config – share this project, visit: http://localhost:9003/nacos/test/1, the results are as follows:

The dynamic refresh configuration will not be demonstrated here, but play it yourself at……

How does Nacos persist?

With all this talk, have you ever wondered where exactly Nacos’s set of configurations are stored?

By default, Nacos uses the embedded database Derby, which can be verified in the /data directory of the nacos-server file, as shown below:

The question is, how can these configurations be stored in their own database?

Currently, Nacos only supports Mysql database, and the version requirement is 5.6.5+

Initializing the database

Create a new database nacos-config in Mysql and execute the SQL script nacos-mysql.sql in the nacos-server folder as shown in the following figure:

When the script is executed, the table is automatically created as shown below:

Modifying a Configuration File

Nacos-server is also a Spring Boot project. If you want to connect to your own database, you need to configure the data source.

The configuration file is also in the conf directory of nacos-server, as shown below:

Just uncomment the Mysql configuration in application.properties and configure your own data source, as shown below:

After the modification, restart nacOS-server.

How do you verify that it’s persistent? Simply create a configuration and check if it exists in the HIS_config_info table as shown below:

How to build a Nacos cluster?

Is really enough, again to pull the skin high usable, is really the head big……….

Nacos recommends cluster deployment to avoid a single point of failure, so how do you build a cluster? Nacos. IO /zh-cn/docs/…

Without further ado, steal an architecture diagram of the official website as follows:

What does the figure above mean? To tell the truth, this document is not really good, many except beginners a look at the meng, please see Chen’s architecture diagram, as follows:

After seeing Chen’s drawing, is it clearer? The requests are forwarded to the Nacos cluster in common with the Nginx cluster, of course, in order to remain highly available, the database must also be in clustered mode.

Nacos officially recommended building cluster mode in Linux, so Chen tried to build cluster mode in Linux environment. Nginx and Mysql are not going to show you how to build a cluster. Instead, we will show you how to build a cluster in Nacos.

Download Nacos for Linux

Download your own version on GitHub. The version Chen uses is 1.2.1. The address is github.com/alibaba/nac…

Find the file with the tar.gz suffix to download as shown below:

Modifying a Configuration File

Due to limited conditions, Chen only started three Nacos service demonstrations on one server. The ports of Nacos are 8848, 8849, and 8850.

Changing the port Number

The default port number of Nacos is 8848, so how to change the port number? Just change server.port in application.properties under conf as shown below:

Modifying Cluster Configurations

So how do you configure the cluster? Conf directory has a cluster.conf.example file, as shown below:

Copy the cluster.conf.example file into the conf directory and set the following parameters:

172.16.1.84:8848
172.16.1.84:8849
172.16.1.84:8850
Copy the code

What does that mean? 172.16.1.84 is the IP address of the server. Enter the IP address of your own server, and the port number of Nacos follows:.

Modifying a data source

This is already covered in the persistence area, just replace the data source in application.properties as shown below:

Start the Nacos

The Nacos cluster has been configured after the above steps. Now start Nacos separately, using the following command:

bash -f ./startup.sh
Copy the code

If the Nacos service is successfully started and accessed on any port, you will see the three nodes built by yourself in the Cluster Management -> Node List, as shown below:

At this point, the Nacos cluster is set up……

In Nginx configuration

Nginx cluster setup is not demonstrated here, directly in the standalone Nginx configuration. Modify the nginx conf file as follows:

Upstream nacos {server 172.16.1.84:8848; Server 172.16.1.84:8849; Server 172.16.1.84:8850; } server{ listen 80; location / { proxy_pass http://nacos; }}Copy the code

I believe everyone can understand, here will not do too much explanation….. After the configuration is complete, start Nginx and go to http://ip/nacos.

Server-addr is configured in the project

Since the cluster has been set up, the project should also be configured. There are two ways, which are described below.

The first configuration mode is directly connected as follows:

spring:
  application:
    Specify the service name, the name in nacOS
    name: nacos-provider
  cloud:
    nacos:
      discovery:
        The IP address in nacOS-server is the port number
        server-addr: 172.161.84.: 8848172.16. 1.84:8849172.16. 1.84:8850
Copy the code

Connect to Nginx directly as follows:

spring:
  application:
    Specify the service name, the name in nacOS
    name: nacos-provider
  cloud:
    nacos:
      discovery:
        The IP address in nacOS-server is the port number
        server-addr: 172.161.84.: 80
Copy the code

conclusion

The only configuration is to set up three Nacos services in cluster.conf. This is the design concept of Nacos, so that developers can get started quickly and focus on business development.

Is Nacos CP or AP?

First, let’s briefly review the concept of CAP, as follows:

  • Consistency (C) : Whether all data backups in a distributed system have the same value at the same time. (Equivalent to all nodes accessing the same latest copy of data)
  • Availability (A) : Whether the cluster can still respond to read/write requests from clients after some nodes fail. (High availability for data updates)
  • Fault tolerance of partitioning (P) : In practical terms, partitioning is equivalent to time-bound requirements for communication. If the system cannot achieve data consistency within the time limit, it means that A partitioning situation has occurred and that it must choose between C and A for the current operation.

In A general distributed system, the priority must be P, and the rest is A choice between C and A.

Of course, different registries follow different CAPS, as follows:

  • Zookeeper: Guaranteed CP and abandoned availability; If the Master node in the ZooKeeper cluster is down, a new leader is elected, which may take a long time. During this process, services are unavailable.
  • Eureka: Guarantee AP, give up consistency; All nodes in the Eureka cluster are equal. Once a node goes down, other nodes are in normal service (once the client discovers the registration failure, it will connect to other nodes in the cluster). Although availability is guaranteed, the data of each node may not be up to date.
  • Nacos: supports both CP and AP. The default is AP and can be switched. In AP mode, a temporary instance is registered. In CP mode, a permanent instance is registered.

Write in the last

Spring Cloud advanced this column has been accumulated for a long time, some time ago has been busy with work, iron fans know that Chen has completed two columns, respectively is the Spring Boot advanced, Mybatis advanced; In short, the original is not easy, and see and cherish, with a praise is virtue oh!!

The above source code has been uploaded to GitHub, and the required reply keyword 9528 can be obtained.