table of Contents
1. What is Nacos
The following part of the explanation is taken from Nacos official documents:
Nacos is committed to helping you discover, configure, and manage microservices. Nacos provides a set of simple and easy-to-use feature sets to help you quickly realize dynamic service discovery, service configuration, service metadata and traffic management.
Nacos helps you build, deliver and manage microservice platforms more agile and easily. Nacos is a service infrastructure for building modern application architectures (such as microservice paradigm, cloud native paradigm) centered on "services".
In fact, Nacos is the combination of the registration center Eureka and Spring Cloud Config configuration center in the first generation of microservices. It is open sourced by the well-known Bat company Alibaba team in China. It is widely used in the second generation of microservices Spring Cloud Alibaba. You can use it. Nacos replaces the two components eureka and config.
Nacos can be distributed 服务注册与发现
and 分布式配置中心动态
managed
Nacos documentation : https://nacos.io/zh-cn/docs/what-is-nacos.html
Spring Cloud Alibaba documentation : Spring Cloud Alibaba Reference Documentation
2. Dependency management
- Spring Boot Version: 2.1.6.RELEASE
- Spring Cloud Version: Spring Cloud Greenwich
- Spring Cloud Alibaba Version: 2.1.1.RELEASE
- Nacos Server Version: 1.2.1
- Java Version: 1.8
3. Nacos-client build
3.1. Create a new SpringBoot project
<?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">
<parent>
<artifactId>springcloud-alibaba-nacos</artifactId>
<groupId>com.bruce.springcloud-alibaba-nacos</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-alibaba-nacos-client</artifactId>
<dependencies>
<!-- springboot 整合web组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- ============ 正式版本start ========= -->
<!-- SpringCloud整合nacos服务发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- SpringCloud整合nacos配置中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
3.2. Configure and connect to nacos-server
Note: The loading order of Spring Boot configuration files: bootstrap.properties -> bootstrap.yml -> application.properties -> application.yml, where bootstrap.properties is configured as the highest priority
The official nacos document requires that the specified configuration file must be placed in bootstrap.properties
or bootstrap.yml
loaded and initialized, because the bootstrap.properties/yml
type of file has the highest priority in the entire SpringBoot application , so we put the configuration files bootstrap.yml
in it.
application.yml
Because the port of the project will not be easily changed after it is in the production environment, there is no need to dynamically manage the configuration
server:
port: 8010
bootstrap.yml
The principle of the process of loading and searching the configuration center file when the project starts:
When the project starts, it will load nacos-config.yaml
the configuration file with the Data ID by default ; if you set the multi-environment configuration profiles.active, this time will not only load nacos-config.yaml
by default , but also load nacos-config-dev.yaml
the file with this name. In multiple environments, two files will be loaded and searched. If multiple environments are not specified, only one will be loaded by default.
You can turn off dynamic refresh by configuring spring.cloud.nacos.config.refresh.enabled=false
Support profile granular configuration
spring-cloud-starter-alibaba-nacos-config
In the load configuration when loaded with not only dataid
for the ${spring.application.name}.${file-extension:properties}
base configuration for the prefix, also loaded dataid for the ${spring.application.name}-${profile}.${file-extension:properties}
base configuration. In daily development, if you encounter different configurations in multiple environments, you can configure it through the $ {spring.profiles.active}
configuration item provided by Spring .
spring.profiles.active=dev
${spring.profiles.active} When specified by the configuration file, it must be placed in the bootstrap.properties file.
A new nacos-config-dev.yaml
basic configuration with dataid: on Nacos is as follows:
Data ID: nacos-config-dev.yaml
Group : DEFAULT_GROUP
配置格式: YAML
配置内容: current.env: develop-env
The screenshot of the project loading process is as follows:
spring:
application:
#对应Nacos Config中的Data ID,不是指服务名,实际服务应用名称以配置中心文件为准
name: nacos-config
cloud:
nacos:
discovery:
#Nacos注册中心地址
server-addr: 127.0.0.1:8848 #,127.0.0.1:8849,127.0.0.1:8850
enabled: true
config:
#Nacos配置中心地址
server-addr: 127.0.0.1:8848 #,127.0.0.1:8849,127.0.0.1:8850
#分组选择
group: DEFAULT_GROUP
#类型(默认加载.properties),默认指定查找nacos-config.yaml
file-extension: yaml
#读取环境配置,指定环境后,还会加载nacos-config-dev.yaml文件
profiles:
active: dev
After the project is successfully started, it will be registered on nacos:
4. Read data on nacos-server
4.1. Dynamic refresh method 1:
@RefreshScope
: Adding this annotation to the class to use the configuration file parameter value will automatically realize dynamic refresh, as long as there is a file change on the nacos-server side, the configuration will be dynamically refreshed.
NacosController
package com.bruce.controller;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @BelongsProject: springcloud-alibaba-nacos
* @BelongsPackage: com.bruce.controller
* @CreateTime: 2021-02-19 10:45
* @Description: TODO
*/
@Slf4j
@RestController
@RefreshScope
public class NacosController {
@Value("${user.name}")
private String userName;
@GetMapping("/getConfig")
public String getConfig() {
log.info("从nacos-server读取的数据=>>>>>: {}", userName);
return userName;
}
}
4.2. Dynamic refresh mode two:
@Slf4j
@RestController
public class HelloController {
@Autowired
private ConfigurableApplicationContext applicationContext;
@GetMapping("/getConfig1")
public String getServerPort(){
String name = applicationContext.getEnvironment().getProperty("user.name");
log.info("内容是===>>>: , {}", name);
return name;
}
}
5. Startup
package com.bruce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
/**
* @BelongsProject: springcloud-alibaba-nacos
* @BelongsPackage: com.bruce
* @CreateTime: 2021-02-18 13:16
* @Description: TODO
*/
@SpringBootApplication
public class AppNacosClient {
public static void main(String[] args) {
SpringApplication.run(AppNacosClient.class);
}
}
6. Test
nacos-server creates a new nacos-config-dev.yaml file
Visit http://127.0.0.1:8010/getConfig to show the following results:
Modify the value of user.name, do not restart the project, visit again:
realize dynamic refresh
7. Summary of Nacos Configuration Center Principle
7.1. When will Md5 change?
In the long polling task, when the server configuration information changes, the client obtains the latest data and saves it in CacheData, and at the same time updates the md5 value of the CacheData, so when the checkListenerMd5 method is executed next time, Comparing the MD5 value of the previous two times, you will find that the md5 value held by the listener is different from the md5 value of CacheData, which means that the configuration information of the server has changed, and you need to update the latest The data is notified to the holder of the Listener.
So far, the complete process of the configuration center has been analyzed. It can be found that Nacos does not send the latest configuration information of the server to the client by pushing, but the client maintains a long polling task and pulls it regularly. The changed configuration information, and then push the latest data to the holder of the Listener.
7.2. Summary
After the relevant configuration items are created on the Nacos server, the client can listen.
The client uses a long polling timed task to check the data of the configuration items it monitors. Once the server data changes, the client will obtain the latest data and save the latest data in a CacheData object Then, the value of the md5 attribute of CacheData will be recalculated. At this time, the Listener bound to the CacheData will trigger the receiveConfigInfo callback.
Taking into account the failure of the server problem, the client will get the latest data will be stored in the local snapshot file in the future will get priority value configuration information from the file, the address of the current snapshot environment: C:\Users\bruceliu\nacos\config\fixed-127.0.0.1_8848_nacos\snapshot\DEFAULT_GROUP
.
7.3. Reference documents
Nacos documentation: https://nacos.io/zh-cn/docs/what-is-nacos.html