Alibaba Nacos configuration center of Spring Cloud series

Introduction to Nacos ...
Introduction to Nacos
Nacos installation
Configure MySQL database
Getting started with Nacos configuration
Core concept of Nacos configuration
Namespace namespace
Group group
configuration management
Authority control
Public configuration
Configure priority
Construction of Nacos cluster environment

Introduction to Nacos

Nacos is an open source tool launched by Alibaba company, which is used to realize service discovery and Configuration management of distributed system. The English full name is Dynamic Naming and Configuration Service. Na is Naming/NameServer, i.e. registration center. co is Configuration, i.e. Configuration center. Service means that the registration / Configuration center takes service as the core. Service is a first-class citizen of the Nacos world.

The official website says that it is easier to build a dynamic service discovery, configuration management and service management platform for cloud native applications.

Nacos is committed to discovering, configuring, and managing microservices. Nacos provides a set of simple and easy-to-use feature sets, which can quickly realize dynamic service discovery, service configuration, service metadata and traffic management.

Nacos can build, deliver, and manage microservice platforms more quickly and easily. Nacos is a service infrastructure for building a modern application architecture centered on "service".

Using Nacos to simplify service discovery, configuration management, service governance and management solutions makes the discovery, management, sharing and composition of microservices easier.

Nacos website: https://nacos.io/zh-cn/

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

Nacos installation

Environmental preparation

Nacos relies on the Java environment to run. If you are building and running Nacos from code, you also need to configure the Maven environment for this, make sure you install and use it in the following version environment:

  • JDK 1.8+;
  • Maven 3.2.x+.

Download source code or installation package

Nacos can be obtained through source code and distribution package.

Source mode

Download the source code from Github.

git clone https://github.com/alibaba/nacos.git cd nacos/ mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U ls -al distribution/target/ // change the $version to your actual path cd distribution/target/nacos-server-$version/nacos/bin

Distribution package method

You can https://github.com/alibaba/nacos/releases Download the latest stable version of the Nacos Server package.

Start server

Linux/Unix/Mac

Start in the directory nacos/bin of Nacos.

Start command (standalone stands for stand-alone mode operation, non cluster mode):

sh startup.sh -m standalone

If you are using the ubuntu system, or the error prompt of the running script cannot be found, you can try to run it as follows:

bash startup.sh -m standalone

Windows

Start command:

cmd startup.cmd

Or double click startup.cmd Run the file.

visit

Visit: http://localhost:8848/nacos/ , the default username / password is nacos/nacos.

Shut down the server

Linux/Unix/Mac

sh shutdown.sh

Windows

cmd shutdown.cmd

Or double click shutdown.cmd Run the file.

Configure MySQL database

Before 0.7 version of Nacos, the embedded database Apache Derby was used by default to store data (the embedded database will start with Nacos without additional installation); support for MySQL data source was added in 0.7 version and later.

MySQL data source

Environment requirements: MySQL 5.6.5 + (it is recommended to use at least the active standby mode or the highly available database for production);

Initialize MySQL database

Create database nacos_config.

SQL source file address: https://github.com/alibaba/nacos/blob/master/distribution/conf/nacos-mysql.sql , or under the directory conf of Nacos server, find nacos-mysql.sql File, run the file, and the result is as follows:

application.properties to configure

Modify nacos/conf/application.properties The following content of the file.

The final modification results are as follows:

#*************** Config Module Related Configurations ***************# ### If user MySQL as datasource: # Specify MySQL as the data source spring.datasource.platform=mysql ### Count of DB: # Number of database instances db.num=1 # Database connection information, if MySQL version 8.0 + needs to add serverTimezone=Asia/Shanghai ### Connect URL of DB: db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=Asia/Shanghai db.user=root db.password=1234

If you use MySQL 8.0 + as I do, there will be an error when you start Nacos. Don't panic. Create the plugins/mysql folder in the Nacos installation directory, and put it in the 8.0 + version of mysql-connector-java-8.0 xx.jar , restart Nacos, and you will be prompted to change the driver class of MySQL.

Getting started with Nacos configuration

Nacos config demo aggregation project. SpringBoot 2.3.0.RELEASE,Spring Cloud Hoxton.SR5 .

Publish configuration

Select the configuration list page of configuration management and click the rightmost + button to create a new configuration.

Nacos Config uses Data ID and Group to determine the configuration.

The figure below shows that the Data Id is product-service.yaml , the group uses the default group, and adds configuration information in yaml format.

project: name: SpringCloudAlibaba org: Aliababa

Get configuration

Create project

Let's create an aggregation project to explain Nacos. First, create a pom parent project.

Add dependency

pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- Project coordinate address --> <groupId>org.example</groupId> <!-- Project module name --> <artifactId>nacos-config-demo</artifactId> <!-- Project version name snapshot version SNAPSHOT,Official version RELEASE --> <version>1.0-SNAPSHOT</version> <!-- inherit spring-boot-starter-parent rely on --> <!-- Use inheritance method to realize reuse, and all inheritable can be used --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> </parent> <!-- The dependent component version number is defined centrally, but is not imported, When a declared dependency is used in a subproject, the version number of the dependency can be omitted, In this way, the dependent versions used in the project can be managed uniformly --> <properties> <!-- Spring Cloud Hoxton.SR5 rely on --> <spring-cloud.version>Hoxton.SR5</spring-cloud.version> <!-- spring cloud alibaba rely on --> <spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version> </properties> <!-- Project dependency management the parent project only declares dependency, and the child project needs to specify the required dependency(Version information can be omitted) --> <dependencyManagement> <dependencies> <!-- spring cloud rely on --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>$</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring cloud alibaba rely on --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>$</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>

Product service

Create project

Create a product service project under the parent project.

Add dependency

Mainly add spring cloud starter Alibaba Nacos config dependency.

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

The complete dependence is as follows:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <!-- Inherit parent dependency --> <parent> <artifactId>nacos-config-demo</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>product-service</artifactId> <!-- Project dependency --> <dependencies> <!-- spring cloud alibaba nacos config rely on --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!-- spring boot web rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- lombok rely on --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- spring boot test rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </project>

configuration file

At bootstrap.yml The address and application name of the Nacos Server configured in.

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 127.0.0.1:8848 # Nacos Server address group: DEFAULT_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties

Note: why configuration is needed spring.application.name , because it is part of the Nacos configuration management dataId field.

In Nacos Spring Cloud, the complete format of dataId is as follows:

$-$.$
  • Prefix defaults to spring.application.name You can also configure the spring.cloud.nacos.config.prefix To configure.
  • spring.profile.active This is the profile corresponding to the current environment. Note: when spring.profile.active When it is empty, the corresponding connector - will also not exist, and the splicing format of dataId will become $. $
  • File extension is the data format of the configuration content, which can be configured through the spring.cloud.nacos.config.file-extension to configure. Currently, only properties and yaml types are supported, and the default is properties.

Control layer

Use Spring's @ Value annotation to get configuration information. The key in ${} corresponds to the configuration content of Nacos configuration center, followed by the default Value.

The configuration is automatically updated by Spring Cloud native annotation @ RefreshScope.

package org.example.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RefreshScope @RestController public class ConfigController { @Value("$") private String projectName; @Value("$") private String projectOrg; @GetMapping("/config") public Map<String, Object> getConfig() { Map<String, Object> configMap = new HashMap(); configMap.put("projectName", projectName); configMap.put("projectOrg", projectOrg); return configMap; } }

Startup class

package org.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProductServiceApplication { public static void main(String[] args) { SpringApplication.run(ProductServiceApplication.class, args); } }

test

Visit: http://localhost:7070/config The results are as follows:

Modify the configuration to the following and republish:

project: name: SpringCloudAlibaba-Nacos org: Aliababa

The console print information is as follows:

c.a.c.n.c.NacosPropertySourceBuilder : Loading nacos data, dataId: 'product-service.yaml', group: 'DEFAULT_GROUP' b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource ] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default o.s.boot.SpringApplication : Started application in 3.356 seconds (JVM running for 50.676) o.s.c.e.event.RefreshEventListener : Refresh keys changed: [project.name]

Visit: http://localhost:7070/config The results are as follows:

Core concept of Nacos configuration

to configure

Why configuration? Concept.

In the process of system development, developers usually separate some parameters and variables that need to be changed from the code for independent management and exist in the form of independent configuration files. The purpose is to make static system artifacts or deliverables (such as WAR, JAR package, etc.) better adapt to the actual physical operating environment. Configuration management is generally included in the process of system deployment, which is completed by system administrator or operation and maintenance personnel. Configuration change is an effective way to adjust the behavior of the system.

configuration management

Multi dimensional management of configuration.

All configuration related activities of system configuration, such as editing, storage, distribution, change management, historical version management, change audit, etc.

Configuration item

A key value pair Key = Value.

A specific configurable parameter and its value field (a key value pair) usually exist in the form of param key = param value. For example, the log output level (loglevel = info|||||||||||||||||||||||||.

config set

Multiple key value pairs, generally referring to a configuration file.

A collection of related or unrelated configuration items is called a configuration set (multiple key value pairs / a configuration file). In a system, a configuration file is usually a configuration set, which contains all aspects of the system configuration. For example, a configuration set may contain configuration items such as data source, thread pool, log level, etc.

Configuration set ID

Give this profile a globally unique ID.

ID of a configuration set in Nacos. Configuration set ID is one of the dimensions of organization partition configuration. Data ID is usually used to organize the configuration set of the partitioning system. A system or application can contain multiple configuration sets, each of which can be identified by a meaningful name. Data ID usually uses Java like package (such as com.taobao.tc.refund.log.level )The naming rules of ensure global uniqueness. This naming rule is not mandatory.

Configure grouping

Multiple configuration files are put together to form a group, which is generally used to distinguish projects. For example, the distinction between multiple applications in a school, teacher application TEACHER_GROUP, student application study_ GROUP.

A set of configuration sets in Nacos is one of the dimensions of organization configuration. The configuration set is grouped by a meaningful string, such as Buy or Trade, to distinguish the configuration set with the same Data ID. When you create a configuration on Nacos, if you do not fill in the name of the configuration group, the name of the configuration group defaults to DEFAULT_GROUP . Common scenarios of configuration grouping: different applications or components use the same configuration type, such as database_url configuration and MQ_topic configuration.

Configuring snapshots

Cache configuration information.

Nacos's CLIENT SDK will generate a snapshot of the configuration locally. When the client cannot connect to the Nacos Server, the configuration snapshot can be used to display the overall disaster recovery capability of the system. The configuration snapshot is similar to the local commit in Git and cache. It will be updated at the right time, but there is no concept of cache expiration.

Namespace

Distinguish environment, such as: dev, test, prod, etc.

Configuration isolation for tenant granularity. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the differentiated isolation of configuration of different environments, such as the isolation of resources (such as configuration, service) of development test environment and production environment.

Best practices

In general, we can define Namespace, Group and DataId as follows:

  • Namespace: represents different environments, such as development, testing, production, etc;
  • Group: represents a project, such as XX logistics project, XX education project;
  • DataId: there are often several applications under each project, and each configuration set (DataId) is the main configuration file of an application

Namespace namespace

The concept of namespace has been introduced earlier, which is used to isolate multiple environments, and the values of the same configuration (such as database data source) of each application in different environments are different. Therefore, we plan for the actual R & D process and environment of enterprise projects.

If a software company has three environments of development, testing and production, then we should establish three namespaces to distinguish.

Create namespace

Click the menu namespace on the left to see that there is a public (reserved space) by default. Click the new namespace on the right to create it.

Create three namespaces, dev (development environment), test (test environment) and prod (production environment), as shown in the following figure.

The final results are as follows:

Specify namespace

If spring.cloud.nacos.config.namespace If no namespace is specified in, the public (reserved space) of Nacos is used. You can also specify a custom namespace as follows:

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

This configuration must be on bootstrap.yml File. spring.cloud.nacos.config.namespace The value of is the ID of the namespace and can be retrieved from the Nacos console. When adding a configuration, do not select another namespace. Otherwise, the configuration will not be retrieved correctly.

Publish configuration

Select the configuration list page of configuration management, select the dev environment, and click the rightmost + button to create a new configuration.

Nacos Config uses Data ID and Group to determine the configuration.

The figure below shows that the Data Id is product-service.yaml , the group uses the default group, and adds configuration information in yaml format.

project: name: SpringCloudAlibaba-DEV org: Aliababa

Get configuration

configuration file

bootstrap.yml

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 127.0.0.1:8848 # Nacos Server address group: DEFAULT_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties namespace: 450a3f07-08ee-49f6-8213-9b04b06cd3cc # Corresponding to dev environment

Control layer

Use Spring's @ Value annotation to get configuration information. The key in ${} corresponds to the configuration content of Nacos configuration center, followed by the default Value.

The configuration is automatically updated by Spring Cloud native annotation @ RefreshScope.

package org.example.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RefreshScope @RestController public class ConfigController { @Value("$") private String projectName; @Value("$") private String projectOrg; @GetMapping("/config") public Map<String, Object> getConfig() { Map<String, Object> configMap = new HashMap(); configMap.put("projectName", projectName); configMap.put("projectOrg", projectOrg); return configMap; } }

test

Visit: http://localhost:7070/config The results are as follows:

Group group

Group group information can be specified when creating a new configuration, as shown in the following figure:

configuration management

In this section, we demonstrate the operation of the console through a large number of pictures.

New / edit / delete / query

Right + new configuration. Single edit or delete edit or delete in the select action bar. After batch deletion is checked, select red in the lower left corner to delete.

It can be configured through Data Id and Group query, and can also export query results.

Import / export / Clone

As mentioned earlier, namespaces are used to isolate multiple environments. The values of the same configuration (such as database data source) of each application in different environments are different. In other words, a large number of configuration items may be the same, and configuration items with individual differences need to be modified additionally. In this case, if one item is added again, it must be very unfriendly, we can implement it through the import and export function.

For example, we export all the configurations in the dev environment.

Then import in the test environment. After the file is uploaded, the configuration will be imported directly. Please be careful!

The same effect can be achieved through cloning. The difference is that cloning can additionally modify Data Id and Group information.

History / rollback

Select the historical version page of configuration management, through Data Id and Group query history, you can view the details of each historical version, or choose to roll back to that version.

Listening query

Nacos provides the ability to configure subscribers, that is, to query listeners. It also provides the MD5 check value currently configured by the Client, so as to help the user better check whether the configuration changes are pushed to the Client.

Select the listening query page of configuration management and query through configuration or IP, Data Id and Group.

Authority control

Nacos provides RBAC based permission control, which is realized by user list, role management and permission management in the left permission control menu. It can be regarded as a fool operation, just a few more mouse clicks.

Public configuration

Each configuration set corresponds to one application. However, during development, we may have some public configurations used by multiple applications. In this case, we need to extend the configuration set or share the configuration set.

Extended configuration set

First, we create three configuration sets, as follows:

Data ID: ext-config-common01.yaml Group: DEFAULT_GROUP Configuration format: YAML Configuration content: common.name: common-service Data ID: ext-config-common02.yaml Group: GLOBAL_GROUP Configuration format: YAML Configuration content: global.name: global-service Data ID: ext-config-common03.yaml Group: REFRESH_GROUP Configuration format: YAML Configuration content: refresh.name: refresh-service

Get configuration

configuration file

bootstrap.yml

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 127.0.0.1:8848 # Nacos Server address group: MALL_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties namespace: 450a3f07-08ee-49f6-8213-9b04b06cd3cc # Corresponding to dev environment # Extended configuration set ext-config[0]: data-id: ext-config-common01.yaml # Configuration set id ext-config[1]: data-id: ext-config-common02.yaml # Configuration set id group: GLOBAL_GROUP # Group, default is DEFAULT_GROUP ext-config[2]: data-id: ext-config-common03.yaml # Configuration set id group: REFRESH_GROUP # Group, default is DEFAULT_GROUP refresh: true # Whether dynamic refresh is supported

Summary:

  • Through configuration spring.cloud.nacos . config.ext -Config [n]. Data ID to support multiple configuration sets.
  • Through configuration spring.cloud.nacos.config.ext-config[n].group to customize the configuration group. If not specified, the default group is used.
  • Through configuration spring.cloud.nacos.config. config[n].refresh to control whether the configuration set supports dynamic refresh of configuration. Not supported by default.

Control layer

Use Spring's @ Value annotation to get configuration information. The key in ${} corresponds to the configuration content of Nacos configuration center, followed by the default Value.

The configuration is automatically updated by Spring Cloud native annotation @ RefreshScope.

package org.example.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RefreshScope @RestController public class ConfigController { @Value("$") private String commonName; @Value("$") private String globalName; @Value("$") private String refreshName; @GetMapping("/extConfig") public Map<String, Object> getExtConfig() { Map<String, Object> configMap = new HashMap(); configMap.put("commonName", commonName); configMap.put("globalName", globalName); configMap.put("refreshName", refreshName); return configMap; } }

test

Visit: http://localhost:7070/extConfig The results are as follows:

Shared configuration set

The shared configuration set can also realize the function of public configuration. The only difference is that the shared configuration set cannot set the group information, only get the DEFAULT_GROUP. The specific implementation is as follows:

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 127.0.0.1:8848 # Nacos Server address group: MALL_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties namespace: 450a3f07-08ee-49f6-8213-9b04b06cd3cc # Corresponding to dev environment # Shared configuration set shared-dataids: ext-config-common01.yaml,ext-config-common02.yaml,ext-config-common03.yaml # Comma separated multiple configuration sets refreshable-dataids: ext-config-common01.yaml # Which configuration set supports dynamic refresh

Visit: http://localhost:7070/extConfig The results are as follows:

Configure priority

Spring Cloud Alibaba Nacos Config provides three functions to pull configuration from Nacos:

  • A: Automatically generate related Data Id configuration through internal related rules (application name, data format of configuration content, etc.);
  • B: Through configuration spring.cloud.nacos . config.ext -Config [n]. Data ID to support multiple configuration sets. When multiple configuration sets are configured at the same time, the priority relationship is determined by the value of N. the larger the value is, the higher the priority is;
  • C: Through configuration spring.cloud.nacos.config.shared-dataids configures multiple shared configuration sets;

When the three methods are used at the same time, the priority relationship is a > b > C.

Construction of Nacos cluster environment

The cluster mode is the same as our usual capacity expansion. It can be forwarded to multiple nodes through Nginx, as shown in the following figure:

For convenience and convenience, you can use the direct connection ip mode. In the configuration, you can write it as follows:

spring: # Configure Nacos configuration center cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 192.168.10.101:8848,192.168.10.102:8848,192.168.10.103:8848 # Nacos server address

PS: if it's just for learning, you can directly start three instances locally by modifying the port. In this paper, three servers are used to build the environment, which is actually simpler.

Environmental preparation

Nacos single node, that is, the standalone mode we just used, uses the embedded database to store data by default, which is not convenient to observe the basic situation of data storage. After version 0.7, the ability to support MySQL data source has been added. When building a cluster, we need to connect Nacos with MySQL for data storage. If you want to build a highly available cluster environment, at least the following conditions should be met:

  • JDK 1.8+;
  • Maven 3.2.x+;
  • MySQL 5.6.5 + (it is recommended to use at least the active / standby mode in production or the highly available database);
  • Only three or more Nacos nodes can form a cluster.

Download source code or installation package

Nacos can be obtained through source code and distribution package.

Source mode

Download the source code from Github.

git clone https://github.com/alibaba/nacos.git cd nacos/ mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U ls -al distribution/target/ // change the $version to your actual path cd distribution/target/nacos-server-$version/nacos/bin

Distribution package method

You can https://github.com/alibaba/nacos/releases Download the latest stable version of the Nacos Server package.

Configure cluster profile

Unzip the installation package.

tar -zxvf nacos-server-1.3.0.tar.gz -C /usr/local/ # Extract the file to the local directory

Copy the configuration file in the directory nacos/conf of Nacos cluster.conf.example And rename to cluster.conf , each line is configured as ip:port. (please configure 3 or more nodes)

192.168.10.101:8848 192.168.10.102:8848 192.168.10.103:8848

Configure MySQL database

Before 0.7 version of Nacos, the embedded database Apache Derby was used by default to store data (the embedded database will start with Nacos without additional installation); support for MySQL data source was added in 0.7 version and later.

MySQL data source

Environment requirements: MySQL 5.6.5 + (it is recommended to use at least the active standby mode or the highly available database for production);

Initialize MySQL database

Create database nacos_config.

SQL source file address: https://github.com/alibaba/nacos/blob/master/distribution/conf/nacos-mysql.sql , or under the directory conf of Nacos server, find nacos-mysql.sql File, run the file, and the result is as follows:

application.properties to configure

Modify nacos/conf/application.properties The following content of the file.

The final modification results are as follows:

#*************** Config Module Related Configurations ***************# ### If user MySQL as datasource: # Specify MySQL as the data source spring.datasource.platform=mysql ### Count of DB: # Number of database instances db.num=1 # Database connection information, if MySQL version 8.0 + needs to add serverTimezone=Asia/Shanghai ### Connect URL of DB: db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=Asia/Shanghai db.user=root db.password=1234

If you use MySQL 8.0 + as I do, there will be an error when you start Nacos. Don't panic. Create the plugins/mysql folder in the Nacos installation directory, and put it in the 8.0 + version of mysql-connector-java-8.0 xx.jar , restart Nacos, and you will be prompted to change the driver class of MySQL.

Start server

Linux/Unix/Mac

Start in the directory nacos/bin of Nacos.

Start command (in no parameter mode, cluster mode):

sh startup.sh

View startup record

Via / nacos/logs/nacos.log (detailed log) or / nacos/conf/start.out (start record) to see if the start is successful.

View command:

tail -f /usr/local/nacos/logs/start.out

Start successful output result:

2020-04-29 22:47:56,204 INFO Nacos is starting... 2020-04-29 22:47:56,556 INFO Nacos logs files: /usr/local/nacos/logs/ 2020-04-29 22:47:56,556 INFO Nacos conf files: /usr/local/nacos/conf/ 2020-04-29 22:47:56,556 INFO Nacos data files: /usr/local/nacos/data/ 2020-04-29 22:47:56,556 INFO Nacos started successfully in cluster mode.

visit

Visit the following link, the default username / password is nacos/nacos:

From the figure below, we can see that there are three cluster nodes, among which 192.168.10.101:8848 is the leader.

Shut down the server

Linux/Unix/Mac

sh shutdown.sh

test

Direct ip mode

Publish configuration

Select the configuration list page of configuration management and click the rightmost + button to create a new configuration.

Data ID: product-service.yaml Group: DEFAULT_GROUP Configuration format: YAML Configuration content: project.name: SpringCloudAlibaba project.org: Aliababa

Get configuration

bootstrap.yml

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 192.168.10.101:8848,192.168.10.102:8848,192.168.10.103:8848 # Nacos server address, cluster direct ip mode group: DEFAULT_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties

Using the previous control layer code, access: http://localhost:7070/config The results are as follows:

Nginx forwarding

Start another server 192.168.10.100, install Nginx, and configure the forwarding rules.

upstream nacos { server 192.168.10.101:8848; server 192.168.10.102:8848; server 192.168.10.103:8848; }

Get configuration

bootstrap.yml

server: port: 7070 # port spring: application: name: product-service # apply name cloud: nacos: config: enabled: true # If you do not want to use Nacos for configuration management, set it to false server-addr: 192.168.10.100:80 # Nacos server address, cluster version Nginx forwarding group: DEFAULT_GROUP # Group, default is DEFAULT_GROUP file-extension: yaml # Configure the data format of the content, default to properties

Using the previous control layer code, access: http://localhost:7070/config The results are as follows:

At this point, all knowledge points of Nacos configuration center are explained.

This paper adopts Intellectual sharing "signature - non-commercial use - no deduction 4.0 international" License Agreement.

You can go through classification See more about Spring Cloud The article.

🤗 Your comments and forwarding are my biggest support.

📢 Scan the code and follow Mr. halloward's "document + video". Each article is provided with a special video explanation, which makes learning easier~

16 June 2020, 03:16 | Views: 1426

Add new comment

For adding a comment, please log in
or create account

0 comments