The project is considering the introduction of a registry and a configuration center. After comparing the current popular configuration centers and registries, IT is found that Nacos is more suitable for our scenario with more private deployment. This article will introduce it, and the following will be studied and shared from the source code implementation level.

I. Comparison with other products

1.1 Comparison with other configuration centers

The current popular configuration center is Apollo, so compare with Apollo.

Compare project/configuration centers Apollo Nacos
High availability Based on the Eureka Raft based, no additional middleware is required
Many environmental In unit of project granularity, there are multiple environments under each project Multiple projects per environment, in units of environment granularity
Configuration to take effect The second-level hot update takes effect The second-level hot update takes effect
Version management Automatic management Automatic management
Configure a rollback support support
Configuration inheritance Support configuration inheritance, can have a common configuration, other to inherit, suitable for microservice scenarios Does not support
Gray released support support
Configuration format verification support support
The audit Audit logs enable you to clearly view the configuration items that are changed during each operation and compare them before and after the changes Audit logs only record the original records before the change, but do not display the changed configuration items and comparison before and after the change
Rights management Authentication is invoked for UI login users and clients in the unit of project granularity. Read-only and read-write permission control is not supported Authentication is invoked for UI login users and clients based on the unit of environment granularity. Read-only and read-write permission control is supported
Listening to the query support support
multilingual Go, C++, Python, Java,.net, OpenAPI Python, Java, Nodejs, Go, OpenAPI
Minimum number of distributed high availability clusters Config2+Admin3+Portal*2+Mysql=8 Nacos*3+MySql=4
Communication protocol HTTP HTTP, gRPC

As you can see, the configuration center has both, and Apollo is more functional than Nacos. However, Apollo relies too much on deployment and has high operating costs. In addition, Apollo is only a configuration center, and Nacos also has a registry. If the service relies on both the registry and the configuration center, only one SET of Nacos can be deployed to meet the requirements, and the operation and maintenance costs are low.

1.2 Comparison with other registries

Compare project \ registry Nacos Eureka Consul
Rely on There is no Zookeeper There is no
CAP model AP+CP AP CP
scalability Raft election algorithm has good performance, availability and fault tolerance Using broadcast synchronization information, a cluster of more than 1000 machines puts a lot of pressure on the Eureka cluster Raft election algorithm
Health Check Methods TPC/HTTP/SQL/Client Beat Client Beat TCP/HTTP/gRPC/CMD
Load Balancing Policy Weight/MetaData/Selector Ribbon Fabio
Cross-center synchronization support Does not support support
Version of the iteration Normal iteration Has not to upgrade Normal iteration
Integration support SpringCloud/K8S SpringCloud SpringCloud/K8S
Access protocol HTTP/DNS/gRPC HTTP HTTP/DNS
Avalanche protection support support Does not support
Automatic logout instance support support Does not support
Listening to the support support support support
interface Chinese English English

As Eureka 2.x is no longer iterated, it will not be selected. Functionally, the Nacos registry will be more complete. In terms of UI, Nacos is a Chinese interface, which is more in line with Chinese people’s habits. Therefore, Nacos is a better choice.

Ii. Principle of Nacos

2.1 System Architecture

The system architecture of Nacos is designed as follows:Logical architecture and components:

The overall architecture is divided into user layer, service layer, kernel layer and plug-in layer. The user layer solves usability problems, the business layer solves service discovery and configuration management functions, the kernel layer solves core problems such as distributed system consistency, storage and high availability, and the plug-in solves scalability problems.

  • User layer: OpenAPI, Console, SDK, Agent, CLI.
  • Business layer: service management, configuration management, metadata management.
  • Kernel layer: plug-in mechanism, event mechanism, logging module, callback mechanism, addressing mode, push channel, capacity management, traffic management, caching mechanism, startup mode, consistency protocol, storage module.
  • Plugins: NameService, CMDB, Metrics, Trace, Access Management, User management, rights management, audit system, notification system.

2.2 Configuration center Design

2.2.1 Configuring the central domain model

  • NameSpace: Used for tenant granularity configuration isolation. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of a Namespace is the isolation of different environment configurations. For example, resources (such as database configurations, traffic limiting thresholds, and degrade switches) in the development test environment and production environment are isolated. If no Namespace is specified, the public Namespace is used by default.
  • Configuration Group: a configuration set in Nacos. It is one of the configuration dimensions. DEFAULT_GROUP is used by default.
  • Configuration ID (Data ID) : indicates the ID of a configuration set in Nacos. It is one of the dimensions for dividing configuration. A system or application can contain multiple configuration sets, and each configuration set can be identified by a meaningful name.

A typical usage scenario is as follows:

2.2.2 Data Consistency

The configuration center uses AP consistency protocol in implementation.

  • For consistency protocols between servers:
    • There is a DB, the core is to ensure that the Server and DB before the data consistency. The data is written to any Server, the data is persisted first, and then the other nodes are asynchronously notified to pull the latest configuration value from the database and notified of the success of the write.
    • Raft protocol is used to ensure data consistency between servers without DB.

  • For the consistency between the Client and Server, check whether the consistency is the MD5 value. If the consistency is not the same, pull the latest value. In 2.x, the client will establish a long connection with the Server and perform a long rotation training every 30 seconds. The Server will push the list of configuration changes and the SDK will pull the configuration updates.

2.2.3 disaster

The Nacos client generates a snapshot of the configuration locally. When the client cannot connect to the Nacos Server, the configuration snapshot can be used to achieve overall disaster recovery capability. It is similar to a cache and will be updated at an appropriate time, but there is no concept of cache expiration.

2.3 Registry design

2.3.1 Registry data model

Nacos is divided into three layers: service, cluster and instance.

  • Services: includes the following contents.
    • Namespace: The top-level concept in the Nacos data model, which can be used in scenarios where the environment or tenants are strongly isolated.
    • Group: An isolation concept inferior to namespace. It is a weak isolation concept. It is mainly used to logically distinguish some service usage scenarios or services with the same name in different applications, such as test groups and production groups of the same service.
    • Service Name: The Name of a service instance that describes the functionality or capability that the service provides.
  • Cluster: A logical abstraction of a group of service instances, between a service and an instance. It is the submergence of some service attributes and the abstraction of instance attributes. It mainly stores information and data about health checks.
    • Health check type: TCP, HTTP, and MySQL are supported. If the value is set to NONE, health check can be disabled.
    • Health check port: Set the port used for health check.
    • Whether to use instance ports for health check: If you use instance ports for health check, the network ports specified in the instance definition are used for health check.
    • Extended data: Metadata content for user-defined extensions in the form of K-V.
  • Instance: a node that provides a specific capability for a service.
    • Instance Definition (Development run scenario)
      • Network IP address: IP address of the instance, which can be set to a domain name after Nacos2.0.
      • Network port: Port information of the instance.
      • Health status: Maintenance is performed by means of health check.
      • Cluster: Identifies the logical Cluster to which the instance belongs.
      • ExtendData: Metadata content in the form k-V for user-defined extensions.
    • Instance metadata (O&M scenario)
    • Weight: floating point number, ranging from 0 to 10000. The greater the weight, the greater the traffic allocated to the instance.
    • Online status: Indicates whether the instance accepts traffic, priority over weight and health status.
    • Extension data: Different from the extension data in the instance definition, this extension data allows operation and maintenance personnel to quickly modify and add the extension data of the instance without changing the instance itself, so as to achieve the function of operation and maintenance of the instance.

2.3.2 consistency

Nacos supports two conformance protocols, AP and CP. In implementation, ONE is CP consistency based on simplified Raft and the other is AP consistency based on Distro (Distro improvement), a self-developed protocol.

2.3.3 persistence

Nacos instances support two types, temporary instances and persistent instances, and the key difference between the two is the health check method. Temporary instances use client-side reporting mode, while persistent instances use server-side reverse detection mode, enabled at the instance level at 1.x and at the service level after 2.x.

2.3.4 heartbeat

As mentioned above, Nacos supports both client-side and server-side health checks. For temporary instances, the heartbeat reporting mode is used to maintain the activity. The default heartbeat sending interval is 5 seconds. The Nacos server will set the instance as unhealthy after 15 seconds when no heartbeat is received, and remove the temporary instance after 30 seconds when no heartbeat is received. For persistent instances, the detection mode supports TCP port detection, HTTP return code detection, and some special scenarios, such as the MySQL command.

Nacos will also support user extension mechanisms in the future, allowing users to pass in a request for business semantics, which will then be executed by Nacos, enabling customization of health checks.

2.3.5 Load Balancing

Load balancing is not a function of the registry. The complete process should be to obtain a list of service instances from the registry, and then select some instances according to actual requirements or access different service providers according to certain traffic distribution mechanism. However, Nacos is just the opposite. Service consumers do not care about load balancing, but only about how to access services correctly and efficiently, while service providers are very concerned about the allocation of their own accessed traffic. In terms of implementation, Nacos combines load balancing between client and server, and provides policies based on health check, weight, CMDB tag and so on.

2.4 Permission Design

Nacos adopts RBAC system in permission design. Authorized resources are namespaces aware, with large granularity and relatively weak functions.

  • List of users

  • Role management

  • Rights management

Three, Nacos installation

3.1 Single-machine Deployment Mode

3.1.1 Using an embedded database

#! /bin/bash # reference address # https://github.com/nacos-group/nacos-docker # Web access http://127.0.0.1:8848, account/password: Nacos/nacos port # 9848 # 8848 for the service for the client gRPC requests the server port, for the client to the server connection and request, the fixed offset 1000, or 8848 + 1000 # 9849 for the service side gRPC request to the server port, used for synchronization between services, etc., # SERVER_SERVLET_CONTEXTPATH: specifies the context prefix, default nacOS # NACOS_APPLICATION_PORT: False # NACOS_AUTH_TOKEN_EXPIRE_SECONDS: specifies the token validity time. The default value is 18000 seconds. Token, the default SecretKey012345678901234567890123456789012345678901234567890123456789 # NACOS_AUTH_CACHE_ENABLE: False # SPRING_DATASOURCE_PLATFORM: specifies the data source platform. If MySQL is used, set the value to MySQL # MYSQL_DATABASE_NUM: # MYSQL_SERVICE_HOST: specifies the database host # MYSQL_SERVICE_PORT: specifies the database port # MYSQL_SERVICE_DB_NAME: specifies the database port. # MYSQL_SERVICE_DB_PARAM: specifies the database connection parameter # MYSQL_SERVICE_USER: specifies the user name # MYSQL_SERVICE_PASSWORD: NACOS_AUTH_TOKEN_EXPIRE_SECONDS: indicates the Token expiration time. The default value is 1800 seconds. NACOS_SERVER_IP: indicates the preferred IP address or network interface card. # JVM_XMS: -xms # JVM_XMX: -xmx # JVM_XMN: -xmn # JVM_MS: -xx :MetaspaceSize # JVM_MMS: -xx :MetaspaceSize # JVM_MMS: - XX: MaxMetaspaceSize # TOMCAT_ACCESSLOG_ENABLED: Docker run -d --name some-nacos -e docker run -d --name some-nacos -e MODE=standalone \ -P 8848:8848 \ -p 9848:9848 \ -P 9849:9849 \ nacOS/nacOS-Server :2.0.3Copy the code

3.1.2 Using the MySQL Database

#! /bin/bash docker run -d \ --name some-nacos-mysql \ --net common-network \ -e MODE=standalone \ -p 8848:8848 \ -p 9848:9848 \ -p 9849:9849 \ -e SPRING_DATASOURCE_PLATFORM=mysql \ -e MYSQL_SERVICE_HOST=some-mysql \ -e MYSQL_SERVICE_PORT=3306 \ -e MYSQL_SERVICE_DB_NAME=nacos \ -e 'MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&al LowPublicKeyRetrieval =true' \ -e MYSQL_SERVICE_USER=nacos \ -e MYSQL_SERVICE_PASSWORD=nacos \ nacOS/nacOS-server :2.0.3Copy the code

3.2 Cluster Deployment Mode

3.2.1 Configuring a Database

Download the distribution package or source code from the Nacos website, go to the nacOS-2.0.3 /distribution/conf directory, and execute the SQL script:

source nacos-mysql.sql
Copy the code

3.2.2 Starting the Nacos instance

A Docker instance node is used for simulation, and the ports are 8841,8842,8843 in sequence. Swarm is not used yet, and the configuration is as follows:

  • nacos-start-8841.sh
#! /bin/bash docker run -d \ --name some-nacos-8841 \ --net common-network \ -h some-nacos-8841 \ -e MODE=cluster \ -e PREFER_HOST_MODE=hostname \ -e 'NACOS_SERVERS=some-nacos-8841:8841 some-nacos-8842:8842 some-nacos-8843:8843' \ -e NACOS_APPLICATION_PORT=8841 \ -p 8841:8841 \ -e SPRING_DATASOURCE_PLATFORM=mysql \ -e MYSQL_SERVICE_HOST=some-mysql \ -e  MYSQL_SERVICE_PORT=3306 \ -e MYSQL_SERVICE_DB_NAME=nacos \ -e 'MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&al lowPublicKeyRetrieval=true' \ -e MYSQL_SERVICE_USER=nacos \ -e MYSQL_SERVICE_PASSWORD=nacos \ -e JVM_XMS=512m \ -e JVM_XMX = 512 m \ - v/Users/ginger/nacos/logs / 8841: / home/nacos/logs \ nacos/nacos - server: the 2.0.3Copy the code
  • nacos-start-8842.sh
#! /bin/bash docker run -d \ --name some-nacos-8842 \ --net common-network \ -h some-nacos-8842 \ -e MODE=cluster \ -e PREFER_HOST_MODE=hostname \ -e 'NACOS_SERVERS=some-nacos-8841:8841 some-nacos-8842:8842 some-nacos-8843:8843' \ -e NACOS_APPLICATION_PORT=8842 \ -p 8842:8842 \ -e SPRING_DATASOURCE_PLATFORM=mysql \ -e MYSQL_SERVICE_HOST=some-mysql \ -e  MYSQL_SERVICE_PORT=3306 \ -e MYSQL_SERVICE_DB_NAME=nacos \ -e 'MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&al lowPublicKeyRetrieval=true' \ -e MYSQL_SERVICE_USER=nacos \ -e MYSQL_SERVICE_PASSWORD=nacos \ -e JVM_XMS=512m \ -e JVM_XMX = 512 m \ - v/Users/ginger/nacos/logs / 8842: / home/nacos/logs \ nacos/nacos - server: the 2.0.3Copy the code
  • nacos-start-8843.sh
#! /bin/bash docker run -d \ --name some-nacos-8843 \ --net common-network \ -h some-nacos-8843 \ -e MODE=cluster \ -e PREFER_HOST_MODE=hostname \ -e 'NACOS_SERVERS=some-nacos-8841:8841 some-nacos-8842:8842 some-nacos-8843:8843' \ -e NACOS_APPLICATION_PORT=8843 \ -p 8843:8843 \ -e SPRING_DATASOURCE_PLATFORM=mysql \ -e MYSQL_SERVICE_HOST=some-mysql \ -e  MYSQL_SERVICE_PORT=3306 \ -e MYSQL_SERVICE_DB_NAME=nacos \ -e 'MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&al lowPublicKeyRetrieval=true' \ -e MYSQL_SERVICE_USER=nacos \ -e MYSQL_SERVICE_PASSWORD=nacos \ -e JVM_XMS=512m \ -e JVM_XMX = 512 m \ - v/Users/ginger/nacos/logs / 8843: / home/nacos/logs \ nacos/nacos - server: the 2.0.3Copy the code

The startup effect is as follows:

To view the Leader node, click on the node metadata to view it. Note that by default, Nacos allocates 2 GB of memory. In a single-node multi-container deployment, you must add the configuration of this environment variable; otherwise, the system will always restart. If the deployment mode is multi-machine and single-container, this operation is not required.

3.3 Configuring the Nginx Proxy

You can configure an Nginx agent for the cluster as a unified entry point for subsequent management and maintenance. Nginx deployment without further elaboration, the configuration is as follows:

location / {
  proxy_pass http://nacos-server;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header REMOTE-HOST $remote_addr;
  add_header X-Cache $upstream_cache_status;
  add_header Cache-Control no-cache;
}
upstream nacos-server {
  server some-nacos-8841:8841 weight=1 max_fails=2 fail_timeout=10s;
  server some-nacos-8842:8842 weight=1 max_fails=2 fail_timeout=10s;
  server some-nacos-8843:8843 weight=1 max_fails=2 fail_timeout=10s;
}
Copy the code

4. Configuration center integration with SpringBoot

4.1 Importing Pom Configuration

The < nacos - config. Version > 0.2.10 < / nacos - config. Version > <! --> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-config-spring-boot-starter</artifactId> <version>${nacos-config.version}</version> </dependency>Copy the code

4.2 Importing the Nacos Configuration

  1. Add the service configuration to application.properties
spring.profiles.active = dev
spring.application.name = easy-console

server.port = 8096
server.servlet.context-path = /console
Copy the code
  1. Application.properties Adds the Nacos configuration
# Nacos configuration center server address Nacos. Config. The server - addr = 172.17.0.26:8848 # whether open Nacos configuration preload Nacos. Config. The bootstrap. Enable = true # Whether open Nacos preload log Nacos. Config. The bootstrap. Log - enable = false # namespace (can only use the namespace Id, do not use the Name, Namespace = dev # Config group nacos.config.group = DEFAULT_GROUP # config item Data Id Nacos.config. data-id = ${spring.application.name}-${spring.profiles. Active}.${nacos.config.type} # Configure the format Nacos.config. type = properties # Whether automatic refresh nacos.config.auto-refresh = true # Whether remote configuration takes precedence over local configuration nacos.config.remote-first = Nacos.config. max-retry = 3 nacos.config.config-retry-time = 2000 nacos.config.config-retry-time = 2000 Config-long-poll-timeout = 30000 # Pull the remote configuration nacos.config.enable-remote-sync-config = false when the listener is first addedCopy the code

Note that nacos. Config. The bootstrap. Enable to open, nacos configuration need to load first, from the remote pull service configuration. Otherwise, some configurations for the service may load first, causing an error because the configuration does not exist.

  1. Service log
[Nacos Config Boot] : The preload log configuration is enabled . ____ _ __ _ _ /\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )___ | '_ | '_| | '_ / _ ` | \ \ \ \ \ / ___) | | _) | | | | | | | (_ | |)))) 'there comes | |. __ _ - | | | _ _ - | | | ___. | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.12. RELEASE) [17:24:24 2021-12-19. 261]. [the main] [INFO] NacosConfigPropertiesUtils buildNacosConfigProperties: 47 - nacosConfigProperties : NacosConfigProperties {serverAddr = '172.17.0.26:8848', contextPath = 'null', encode = 'null', the endpoint = 'null', namespace='null', accessKey='null', secretKey='null', ramRoleName='null', autoRefresh=true, dataId='easy-console-dev.properties', dataIds='null', group='DEFAULT_GROUP', type=PROPERTIES, maxRetry='3', configLongPollTimeout='30000', configRetryTime='2000', enableRemoteSyncConfig=false, extConfig=[], bootstrap=Bootstrap{enable=true, LogEnable = true}} [17:24:24 2021-12-19. 270]. [the main] [INFO] ClientWorker addCacheDataIfAbsent: 384 - [config_rpc_client] [the subscribe] easy - the console - dev. Properties + DEFAULT_GROUP [17:24:24 2021-12-19. 277]. [the main] [INFO] CacheData addListener: 169 - [config_rpc_client] [add-listener] ok, tenant=, dataId=easy-console-local.properties, group=DEFAULT_GROUP, CNT = 1 [17:24:24 2021-12-19. 285]. [the main] [INFO] StartupInfoLogger logStarting: 55 - Starting EasyConsoleApplication on PC. The local with PID 88943 [17:24:24 2021-12-19. 286]. [The main] [INFO] SpringApplication logStartupProfileInfo: 652 - The following profiles are active: Dev [the 2021-12-19 17:24:26. 526] [the main] [INFO] TomcatWebServer. The initialize: 108 - Tomcat initialized with the port (s) : 8096 (HTTP) [2021-12-19 17:24:26.534] [main] [INFO] DirectJDklog. log:173 - Initializing ProtocolHandler [" http-NIO-8096 "] [2021-12-19 17:24:26.534] [main] [INFO] Directjdklog. log: 173-starting service [Tomcat] [2021-12-19 17:24:26.534] [main] [INFO] directjdklog. log: 173-starting Servlet Engine: [Apache Tomcat/9.0.46]Copy the code
  1. Configure central client logs
2021-12-24 14:37:09.268 INFO [main: c.A.n.c.U.aramutil] [Settings] [req-serv] nacos-server port:8848 2021-12-24 14:37:09.271 INFO [main: c.A.n.c.u.aramutil] [Settings] [http-client] Connect Timeout :1000 2021-12-24 14:37:09.273 INFO  [main :c.a.n.c.u.ParamUtil] PER_TASK_CONFIG_SIZE: 3000.0 the 2021-12-24 14:37:09. 376 INFO [main: C.A.N.C.I.C redentialWatcher] null No credential found the 2021-12-24 14:37:09. 408 INFO [main: c.a.n.c.C.I.LIMiter] limitTime:5.0 2021-12-24 14:37:09.904 INFO [main : C.A.N.C.C.I.L ocalConfigInfoProcessor] LOCAL_SNAPSHOT_PATH: logs/nacos/config 14:37:10. 2021-12-24 835 INFO [com.alibaba.nacos.client.remote.worker:c.a.n.c.c.i.ClientWorker] [e12d9f10-6594-4ddc-8dc2-fc4a6d48e5a9_config-0] Connected,notify listen context... 2021-12-24 14:37:10.891 INFO [main: c.A.n.c.c.u.jvmutil] isMultiInstance:false 2021-12-24 14:37:10.906 INFO [main :c.a.n.c.c.i.ClientWorker] [config_rpc_client] [subscribe] easy-console-dev.properties+DEFAULT_GROUP+dev 2021-12-24 14:37:10.911 INFO [main: C.A.N.C.C.I.C acheData] [config_rPC_client] [add-listener] OK, tenant=dev, dataId=easy-console-local.properties, group=DEFAULT_GROUP, cnt=1Copy the code
  1. Other environment startup

There are two ways to achieve this. The first way is to use a set of configuration center and switch the environment by starting the command as follows:

-Dspring.profiles.active=online
Copy the code

The second method is as follows:

4.3 Nacos Cache files

Nacos will cache the remote configuration locally. The default directory is/user directory. Nacos will concatenate/Nacos /config after the default directory as follows:

ginger@pc:~ $├─ config │ ├── config_rpc_custom │ ├── local │ ├─ │ ├ ─ 08.08.00 (08.08.00) ├ ─ 08.08.00 (08.08.00Copy the code

You can change the location of the cache file by adding the -d parameter to the startup script.

  • Jm.snapshot. PATH, specifies the cache file storage location, default/ User directory, so the actual directory is/${JM.SNAPSHOT.PATH}/nacos/config.

4.4 Nacos Client Logs

Nacos will log the client. The default directory is/user directory. Nacos will concatenate /logs/ Nacos after the default directory as follows:

ginger@pc:~ $tree logs ├── nacos ├─ config.log ├── name.log ├── page.txtCopy the code

The default size of a single file is 10 MB. A maximum of seven files can be created. You can add the -d parameter to the startup script to change the log storage location, file size, and number of files.

  • Jm.log. PATH, which specifies the Nacos LOG storage location. The default is/ User directory, so the actual directory is/${JM.LOG.PATH}/logs/nacos.
  • Jm.log.retain.COUNT indicates the number of retained LOG files. The default value is 7.
  • Jm.log.file. SIZE, the SIZE of a single LOG FILE, 10M by default.

5. Registry integration with SpringBoot

5.1 Importing Pom Configuration

The < nacos - discovery. Version > 0.2.10 < / nacos - discovery. Version > <! --> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-discovery-spring-boot-starter</artifactId> <version>${nacos-discovery.version}</version> </dependency>Copy the code

5.2 the Provider configuration

  1. Add the service configuration to application.properties
spring.profiles.active = dev
spring.application.name = easy-console

server.port = 8096
server.servlet.context-path = /console
Copy the code
  1. Application.properties Adds the Nacos configuration
Discovery. Server-addr = 172.17.0.26:8848 # Whether to enable automatic registration Nacos. Discovery Registration packet nacos. Discovery. Register. The group - name = DEFAULT_GROUP nacos # registered namespace. The discovery. The namespace = ${spring. Profiles. The active}Copy the code
  1. Service startup log (last line)
. ____ _ __ _ _ / \ / ___ '_ __ _ _) (_ _ __ __ _ \ \ \ \ (() ___ |' _ | '_ | |' _ / _ ` | \ \ \ \ \ / ___) | | _) | | | | | | | (_| | ) ) ) ) ' |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.12. RELEASE) [2021-12-24 14:37:09. 229]. [the main] [INFO] NacosConfigPropertiesUtils buildNacosConfigProperties: 47 - nacosConfigProperties : NacosConfigProperties {serverAddr = '172.17.0.26:8848', contextPath = 'null', encode = 'null', the endpoint = 'null', namespace='local', accessKey='null', secretKey='null', ramRoleName='null', autoRefresh=true, dataId='easy-console-dev.properties', dataIds='null', group='DEFAULT_GROUP', type=PROPERTIES, maxRetry='3', configLongPollTimeout='30000', configRetryTime='2000', enableRemoteSyncConfig=false, extConfig=[], bootstrap=Bootstrap{enable=true, LogEnable =false}} [2021-12-24 14:37:09.974] [main] [INFO] Reflections. Scan :232 - Reflections took 33 ms to scan 1 urls, Produces 3 keys and 6 values [2021-12-24 14:37:09.99] [main] [INFO] Reflections. Scan :232 - Reflections took 14 ms to scan 1 urls, Produces 4 keys and 9 values [2021-12-24 14:37:10.014] [main] [INFO] Reflections. Scan :232 - Reflections took 12 ms to scan 1 urls, Produces 3 keys and 10 values [2021-12-24 14:37:10.140] [main] [INFO] Reflections. Scan :232 - Reflections took 122 ms to  scan 126 urls, Produces 0 keys and 0 values [2021-12-24 14:37:10.155] [main] [INFO] Reflections. Scan :232 - Reflections took 12 ms to scan 1 urls, Produces 1 keys and 5 values [2021-12-24 14:37:10.168] [main] [INFO] Reflections. Scan :232 - Reflections took 10 ms to scan 1 urls, Produces 1 keys and 7 values [2021-12-24 14:37:10.177] [main] [INFO] Reflections. Scan :232 - Reflections took 7 ms to scan 1 urls, Produces 2 keys and 8 values [2021-12-24 14:37:10.270] [main] [INFO] Reflections. Scan :232 - Reflections took 88 ms to scan 126 urls, Producing 0 keys and values 0 [the 2021-12-24 14:37:10. 901]. [the main] [INFO] NacosConfigLoader reqNacosConfig: 169 - load config  from nacos, data-id is : easy-console-dev.properties, group is : DEFAULT_GROUP [the 2021-12-24 14:37:10. 918]. [the main] [INFO] StartupInfoLogger logStarting: 55 - Starting EasyConsoleApplication On The PC. The local with PID 13082 [The 2021-12-24 14:37:10. 921]. [The main] [INFO] SpringApplication logStartupProfileInfo: 652 - The following profiles are active: Local [14:37:12 2021-12-24. 854] [the main] [INFO] TomcatWebServer. The initialize: 108 - Tomcat initialized with the port (s) : 8096 (HTTP) [2021-12-24 14:37:12.861] [main] [INFO] DirectJDklog. log:173 - Initializing ProtocolHandler [" http-NIO-8096 "] [2021-12-24 14:37:12.861] [main] [INFO] Directjdklog. log: 173-starting service [Tomcat] [2021-12-24 14:37:12.862] [main] [INFO] directjdklog. log: 173-starting Servlet engine: [Apache Tomcat/9.0.46] [2021-12-24 14:37:12.924] [main] [INFO] Directjdklog. log: 173-initializing Spring Embedded WebApplicationContext [2021-12-24 14:37:12.925] [main] [INFO] ServletWebServerApplicationContext.prepareWebApplicationContext:285 - Root WebApplicationContext: Initialization Completed in 1964 MS [2021-12-24 14:37:15.823] [main] [INFO] Directjdklog. log: 173-starting ProtocolHandler [HTTP - nio - 8096 ""] [14:37:15 2021-12-24. 837] [the main] [INFO] TomcatWebServer. Start: 220 - Tomcat started on port(s): 8096 (HTTP) with context Path '/console' [2021-12-24 14:37:15.886] [main] [INFO] NacosDiscoveryAutoRegister.onApplicationEvent:89 - Finished auto register service : easy-console, ip : 10.242.44.123, port: 8096Copy the code
  1. Nacos client logs
2021-12-24 14:37:14.700 INFO [main: C.A.N.C. aming] Initializer Namespace from System Property: NULL 2021-12-24 14:37:14.701 INFO [main: C.A.N.C. aming] Initializer namespace from System Environment: NULL 2021-12-24 14:37:14.701 INFO [main: C.A.N.C. aming] Initializer Namespace from System Property: NULL 2021-12-24 14:37:15.839 INFO [main :c.a.n.c.naming] [REGISTER-SERVICE] local registering service easy-console with instance Instance{instanceId='', IP ='10.242.44.123', port=8096, weight=1.0, healthy=true, enabled=true, ephemeral=true, clusterName='null', serviceName='null', The metadata = {preserved. Register. Source = SPRING_BOOT}} 2021-12-24 14:37:16. 108 INFO [main: C.A.N.C.N aming] [register - SERVICE] Local alarm service easy-console with instance instance {instanceId= ", IP ='10.242.44.123', alarm port=8096, Weight =1.0, healthy=true, enabled=true, ephemeral=true, clusterName='null', serviceName='null' metadata={preserved.register.source=SPRING_BOOT}}Copy the code
  1. The boot mode of other environments is the same as that of the configuration center
  2. Page registration effect

5.3 Consumer configuration

  1. Application.properties Adds the service configuration itself
spring.profiles.active = dev
spring.application.name = nacos-client

server.port = 8090
Copy the code
  1. Application.properties Adds the Nacos configuration
Discovery. Server-addr = 172.17.0.26:8848 # Enable automatic registration Nacos. Discovery Registration packet nacos. Discovery. Register. The group - name = DEFAULT_GROUP nacos # registered namespace. The discovery. The namespace = ${spring. Profiles. The active}Copy the code
  1. Obtain the Provider service instance
@NacosInjected private NamingService namingService; / / get all the instances of services namingService. GetAllInstances (" easy - the console ");Copy the code
  1. Invoking the Provider interface (Using the health check interface as an example)
@Slf4j @Component public class HealthCheckTiming { @NacosInjected private NamingService namingService; @Scheduled(cron = "0/5 * * * * ?" ) public void checkHealth() { try { Instance instance = namingService.selectOneHealthyInstance("easy-console", true); String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/console/api/system/status"; String rsp = HttpUtil.getMethod(url); log.info("check health, success, rsp={}", rsp); } catch (IllegalStateException e) { log.info("check health, failed, {}", e.getMessage()); } catch (Exception e) { log.error("check health, failed", e); }}}Copy the code

To use it, you need to catch an IllegalStateException. According to the Nacos source code, Nacos will throw an IllegalStateException when the service instance cannot be obtained.

public static List<Instance> selectAll(ServiceInfo serviceInfo) {
  List<Instance> hosts = serviceInfo.getHosts();
  if (CollectionUtils.isEmpty(hosts)) {
    throw new IllegalStateException("no host to srv for serviceInfo: " + serviceInfo.getName());
  }
  return hosts;
}
Copy the code
  1. Consumer page effect

We found that the application displayed is unknown. Take a look at the Nacos source code, Nacos will read project. Name in the system attribute first as the application name of Consumer. Therefore, if you want to change the application name displayed by Consumer, you only need to add the corresponding parameter to the service startup parameter, such as -dproject.name =nacos-client.

private static final String PARAM_MARKING_PROJECT = "project.name"; private static final String PARAM_MARKING_JBOSS = "jboss.server.home.dir"; private static final String PARAM_MARKING_JETTY = "jetty.home"; private static final String PARAM_MARKING_TOMCAT = "catalina.base"; private static final String DEFAULT_APP_NAME = "unknown"; public static String getAppName() { String appName; appName = getAppNameByProjectName(); if (appName ! = null) { return appName; } appName = getAppNameByServerHome(); if (appName ! = null) { return appName; } return DEFAULT_APP_NAME; } private static String getAppNameByProjectName() { return System.getProperty(PARAM_MARKING_PROJECT); } private static String getAppNameByServerHome() { String serverHome = null; if (SERVER_JBOSS.equals(getServerType())) { serverHome = System.getProperty(PARAM_MARKING_JBOSS); } else if (SERVER_JETTY.equals(getServerType())) { serverHome = System.getProperty(PARAM_MARKING_JETTY); } else if (SERVER_TOMCAT.equals(getServerType())) { serverHome = System.getProperty(PARAM_MARKING_TOMCAT); } if (serverHome ! = null && serverHome.startsWith(LINUX_ADMIN_HOME)) { return StringUtils.substringBetween(serverHome, LINUX_ADMIN_HOME, File.separator); } return null; }Copy the code

Start the service again with the application name changed.

  1. Verify that the Provider service is offline

When the Provider takes the service offline and there is no instance of the Provider available, we see that the Consumer immediately realizes that Nacos will throw no host to SRV for serviceInfo: Easy-console. Then, re-cap the instance and we can see that the Provider can provide services normally.

[the 2021-12-25 16:40:40. 023]. [taskScheduler - 2] [INFO] HealthCheckTiming checkHealth: 34 and check the health, success, RSP = "{" status" : "online"} "[the 2021-12-25 16:40:45. 022]. [taskScheduler - 2] [INFO] HealthCheckTiming checkHealth: 34 - check health, success, RSP = "{" status" : "online"} "[the 2021-12-25 16:40:50. 004]. [taskScheduler - 2] [INFO] HealthCheckTiming checkHealth: 36 - check health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:40:55. 006] [INFO] [taskScheduler - 1] HealthCheckTiming. CheckHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:00. 001]. [taskScheduler - 4] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:05. 002]. [taskScheduler - 4] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:10. 006]. [taskScheduler - 4] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:15. 005]. [taskScheduler - 4] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:20. 006]. [taskScheduler - 4] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:25. 004]. [taskScheduler - 2] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:30. 004]. [taskScheduler - 2] [INFO] HealthCheckTiming checkHealth: 36 - check the health, failed, no host to srv for serviceInfo: Easy - the console [the 2021-12-25 16:41:35. 036] [taskScheduler - 3] [INFO] HealthCheckTiming. CheckHealth: 34 and check the health, success, RSP = "{" status" : "online"} "[the 2021-12-25 16:41:40. 025] [taskScheduler - 3] [INFO] HealthCheckTiming. CheckHealth: 34 - check health, success, rsp="{"status":"online"}"Copy the code

reference

  • Nacos document
  • Nacos official design document
  • Ctrip Apollo configuration center architecture in-depth analysis