Nacos introduction
Nacos is an open source tool launched by Alibaba, which is used to realize service discovery and configuration management of distributed system. Full English name: Dynamic Naming and Configuration Service. Na: Naming/NameServer: registry. Co: Configuration: Configuration center. Service means that the registry/configuration center is service-centric. Service is a first-class citizen of the Nacos world. (The article is reprinted by self fun byte)
Here’s what the website says: a dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications.
Nacos is dedicated to discovering, configuring, and managing microservices. Nacos provides a set of easy-to-use features to quickly implement dynamic service discovery, service configuration, service metadata, and traffic management.
Nacos makes it easier and more agile to build, deliver, and manage microservices platforms. Nacos is a service infrastructure for building a “service” -centric modern application architecture.
Make it easier to discover, manage, share, and compose microservices with Nacos’s solution to simplify service discovery, configuration management, service governance, and management.
Nacos installation
Environment to prepare
Nacos relies on the Java environment to run. If you are building and running Nacos from code and need to configure the Maven environment for this, make sure it is installed in the following versions of the environment:
- The JDK 1.8 +;
- Maven 3.2 x +.
Download the source code or installation package
Nacos can be obtained from both source and distribution.
Source way
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
Copy the code
Distribution package mode
You can visit github.com/alibaba/nac… Download the latest stable nacos-server package.
Starting the server
Linux/Unix/Mac
In the Nacos decompression directory Nacos /bin directory to start.
Start command (standalone stands for running in single-machine mode, not cluster mode) :
sh startup.sh -m standalone
Copy the code
If you are using Ubuntu, or if you are running the script and an error message is not found, try the following:
bash startup.sh -m standalone
Copy the code
Windows
Start command:
cmd startup.cmd
Copy the code
Or double-click startup. CMD to run the file.
access
Shut down the server
Linux/Unix/Mac
sh shutdown.sh
Copy the code
Windows
cmd shutdown.cmd
Copy the code
Or double-click shutdown.cmd to run the file.
Configuring the MySQL Database
Nacos, prior to version 0.7, uses the embedded database Apache Derby by default to store data (the embedded database starts with Nacos and requires no additional installation); In version 0.7 and later, support for MySQL data sources has been added.
MySQL data source
Environment requirements: MySQL 5.6.5+ (At least active/standby mode or high availability database is recommended for production);
Example Initialize the MySQL database
Create database nacos_config.
SQL source file address: private message I obtain, or in nacos-server decompression directory conf, find the nacos-mysql. SQL file, run the file, the result is as follows:
Application. The properties configuration
Modify nacos/conf/application. The properties file of the following content.
The final modification results are as follows:
#*************** Config Module Related Configurations ***************#
### If user MySQL as datasource:
# Specify data source as MySQL
spring.datasource.platform=mysql
### Count of DB:
# Number of database instances
db.num=1
ServerTimezone =Asia/Shanghai for MySQL 8.0+
### 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
Copy the code
If you are using MySQL 8.0+, as I am, you will definitely get an error when starting Nacos. Create a new plugins/mysql folder in the Nacos installation directory and put the mysql-connector-java-8.0.xx.jar version 8.0+ into it. Restart Nacos. The MySQL driver class has been changed.
Getting started with Nacos configuration
Nacos-config-demo aggregation project. SpringBoot 2.3.0.RELEASE, Spring Cloud hoxton.sr5.
Release configuration
On the configuration list page of configuration Management, click the + button on the right to create a configuration.
Nacos Config uses the Data ID and Group to determine the configuration.
The following figure shows that the Data Id is product-service.yaml, the default group is used, and the configuration information in YAML format is added.
project:
name: SpringCloudAlibaba
org: Aliababa
Copy the code
Access to the configuration
Create a project
Let’s create an aggregation project to explain Nacos, first by creating a POM parent project.
Add the dependent
pom.xml
<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 RELEASE -->
<version>1.0 the SNAPSHOT</version>
<! -- inherits the spring-boot-starter parent dependency -->
<! -- Use the inheritance method, realize reuse, inheritance can be used -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0. RELEASE</version>
</parent>
<! Define the version number of the dependent components in a centralized manner, but do not import the version number of the dependent components. When the declared dependencies are used in the sub-project, the version number of the dependency can not be added, so as to unify the management of the dependency versions used in the project.
<properties>
<! -- Spring Cloud hoxton.sr5 dependency -->
<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
<! -- Spring Cloud alibaba dependency -->
<spring-cloud-alibaba.version>2.1.0. RELEASE</spring-cloud-alibaba.version>
</properties>
<! The parent project only declares the dependencies, and the child project specifies the required dependencies (omitted version information) -->
<dependencyManagement>
<dependencies>
<! -- Spring Cloud dependency -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<! -- Spring Cloud alibaba dependency -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Copy the code
Product-service
Create a project
Create a product-service project under the parent project.
Add the dependent
Add spring-cloud-starter- alia-nacos-config dependencies.
<! -- Spring Cloud Alibaba nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Copy the code
The full dependency is as follows:
<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">
<! -- Inheriting parent dependencies -->
<parent>
<artifactId>nacos-config-demo</artifactId>
<groupId>org.example</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-service</artifactId>
<! -- Project dependency -->
<dependencies>
<! -- Spring Cloud Alibaba nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<! -- Spring Boot Web dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! -- Lombok dependency -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<! -- Spring Boot test dependencies -->
<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>
Copy the code
The configuration file
Configure the address and application name of the Nacos Server in bootstrap.yml.
server:
port: 7070 # port
spring:
application:
name: product-service # Application name
cloud:
nacos:
config:
enabled: true If you do not want to use Nacos for configuration management, set this to false
server-addr: 127.0. 01.: 8848 # Nacos Server address
group: DEFAULT_GROUP # group, default is DEFAULT_GROUP
file-extension: yaml # Configure the data format of the content, which defaults to Properties
Copy the code
Note: You need to configure spring.application.name because it is part of the Nacos configuration management dataId field.
In Nacos Spring Cloud, the complete dataId format is as follows:
${prefix}-${spring.profile.active}.${file-extension}
Copy the code
prefix
The default isspring.application.name
, or through the configuration itemspring.cloud.nacos.config.prefix
To configure.spring.profile.active
That is, the profile corresponding to the current environment.Note: whenspring.profile.active
Is empty, the corresponding connection-
The dataId concatenation format will become${prefix}.${file-extension}
file-exetension
To configure the data format of the content, you can run the configuration itemspring.cloud.nacos.config.file-extension
To configure. Currently only supportsproperties
和yaml
Type, default isproperties
.
Control layer
Use Spring’s @value annotation to get the configuration information. ${} corresponds to the key of the Nacos configuration center configuration, followed by the default Value.
The configuration is automatically updated through the 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("${project.name:}")
private String projectName;
@Value("${project.org:}")
private String projectOrg;
@GetMapping("/config")
public Map<String, Object> getConfig(a) {
Map<String, Object> configMap = new HashMap();
configMap.put("projectName", projectName);
configMap.put("projectOrg", projectOrg);
returnconfigMap; }}Copy the code
Start the 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); }}Copy the code
test
Modify the configuration to the following content and republish it:
project:
name: SpringCloudAlibaba-Nacos
org: Aliababa
Copy the code
The following information is displayed on the console:
c.a.c.n.c.NacosPropertySourceBuilder : Loading nacos data, dataId: 'product-service.yaml', group: 'DEFAULT_GROUP' b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-product-service.yaml'}] 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.E vent. RefreshEventListener: Refresh keys changed: [project.name]Copy the code
Half of this article is still unpublished! Click attention to see the follow-up yo article reproduced from the joy byte