当前位置:网站首页>Detailed introduction to the usage of Nacos configuration center
Detailed introduction to the usage of Nacos configuration center
2022-07-03 02:06:00 【Zhang weipeng】
The last article introduced Nacos Usage as a registry , besides ,Nacos It can also be used as a configuration center , Then this article will introduce Nacos As the basic usage of configuration center , First, let's understand why we need to use the configuration center .
One 、 Why configure the center :
Before there is no configuration center , The traditional application configuration has the following pain points :
(1) Adopt local static configuration , There's no guarantee of real-time : Modifying the configuration is not flexible and requires a long test release cycle , Unable to notify the client as soon as possible , Some configurations require high real-time performance , For example, the configuration of active / standby switchover or the configuration needs to be modified in case of failure , At this time, configure through traditional static configuration or republishing , Then the response speed is very slow , Business risks are very high
(2) Easy to cause production accidents : For example, when publishing , It is easy to bring the configuration of the test environment to production , Cause production accidents .
(3) The configuration is messy and the format is not standard : Some use properties Format , Some use xml Format , There are still deposits DB, Teams tend to make their own wheels , There are various methods .
(4) The configuration lacks security audit 、 version control 、 Configure permission control function : who ? At what time ? What configuration has been modified ? There is no way to trace , If something goes wrong, you can't rollback to the previous version in time ; Unable to authenticate and authorize the release of configuration changes , Everyone can modify and publish the configuration .
The configuration center is different from the traditional way that the configuration information is distributed to all corners of the system , Centralized and unified management of configuration files in the system , There is no need to manage individual servers one by one . So what's the advantage of doing this ?
(1) Through the configuration center , It can standardize the configuration 、 Unified format
(2) When the configuration information changes , Changes take effect in real time , There is no need to restart the server , Can automatically perceive the corresponding changes , And send the new changes to the corresponding procedures , Respond quickly to change . For example, a function is only for users in a certain region , There is also a function that is only available during the promotion period , After using the configuration center, only relevant personnel need to dynamically adjust parameters in the configuration center , Basically, you can adjust the corresponding business in real time or quasi real time .
(3) The audit function can also trace the problem
Two 、Nacos Use of configuration center :
There are three main solutions for configuration center in microservices :Nacos、Apollo、Config+Bus, However, this article mainly introduces Nacos Usage as configuration center , Readers who are interested in the other two ways should check online by themselves
1、Springboot Integrate Nacos Configuration center :
(1) First, we declare the version information of the project :
<properties>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
</properties>
<!-- Only declare dependencies , Do not introduce dependencies -->
<dependencyManagement>
<dependencies>
<!-- Statement springBoot edition -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Statement springCloud edition -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Statement springCloud Alibaba edition -->
<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>(2) add to nacos Configuration center maven rely on :
<!-- SpringCloud Ailibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>(3) stay application.properties Add... To the file nacos Configuration center related configuration :
spring.profiles.active=dev
spring.application.name=cloud-producer-server
server.port=8080
# nacos Configure center address
spring.cloud.nacos.config.server-addr=localhost:8848
# The type of configuration file
spring.cloud.nacos.config.file-extension=yaml(4) stay nacos Create a new console DataID by cloud-producer-server-dev.yaml Configuration set of :
Why? DataID The named cloud-producer-server-dev.yaml We'll talk about


(5) Writing test classes :
// After configuration Publishing , Dynamic refresh configuration
@RefreshScope
@RestController
@RequestMapping("provider")
public class ProviderController
{
// Use native annotations @Value() Import configuration
@Value("${user.id}")
private String id;
@Value("${user.name}")
private String name;
@Value("${user.age}")
private String age;
@GetMapping("getNacosConfig")
public String providerTest()
{
return " I am a provider, Successfully obtained nacos Configure the data of the center :(id:" + id + ",name:" + name + ",age:" + age +")";
}
}(6) Start service validation :
Start project , visit http://localhost:8080/provider/getNacosConfig Interface , You can see nacos The configuration information of the configuration center has been effective and successfully obtained

(7) Verify the dynamic refresh configuration :
Dynamic refresh of configuration is one of the core functions of the configuration center , Suppose I need to modify it now user.name Value , Then I'll just change Nacos Will the configuration in take effect ? Let's try to directly Nacos Change the configuration in to “zhangsan”, Here's the picture :

At this time, do not restart the project and re access the interface , give the result as follows :

We found that the configuration has been refreshed dynamically , Why is that ? In fact, it's because we added @RefreshScope The effect of annotation .
// After configuration Publishing , Dynamic refresh configuration
@RefreshScope
@RestController
@RequestMapping("provider")
public class ProviderController2、Nacos Core concept of :
2.1、Data ID:
(1)Data ID Naming format for :
Previously we demonstrated in nacos Create a new console DataID by cloud-producer-server-dev.yaml Data set of , So this Data ID What is it? ?Data ID Is the unique identification of the configuration set , An application can contain multiple configuration sets , Each configuration set needs to be identified by a meaningful name . that Data ID How to get the value ? The popular format is “ Prefix - Environmental Science - Extension ”, As shown below :
${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
① prefix: Prefix , The default is spring.application.name Value , You can also configure items through spring.cloud.nacos.config.prefix To configure the .
# If not specified , The default scheme is the application name
spring.application.name=cloud-producer-server
# Manually specify the configuration dataID Prefix identification
# spring.cloud.nacos.config.prefix=cloud-producer-server-config② active: Configure the operating environment , That is, the current environment corresponds to profile.
Be careful : When spring.profiles.active It's empty time , Corresponding connector ”-“ There will be no ,dataId The splicing format of becomes ${prefix}.${file-extension}
# dev Represents the development environment
spring.profiles.active=dev③ file-exetension: The type of configuration file , The default is properties, You can also configure items through spring.cloud.nacos.config.file-extension To configure the , At present, the supported types are TEXT、JSON、XML、YAML、HTML、Properties
# Specify the configuration file type as yaml file
spring.cloud.nacos.config.file-extension=yaml④ Final configuration :
Go through the first three steps , We ended up with nacos The new configuration file on the console of the configuration center is :cloud-producer-server.yaml
2.2、 Environmental isolation - Namespace Namespace:
Nacos Introduce namespace Namespace To manage and isolate multiple environment configurations and services . for example , You may have a local development environment dev、 Test environment test、 Production environment prod Three different environments , Then you can create three different Namespace Distinguish between different environments . Create it as follows :

After creation , You can go to Nacos You can see different namespaces on the configuration list of the console , Here's the picture :


After successfully creating the new namespace , You can go to springboot Configuration file configuration namespace id Switch to the corresponding namespace , And get the configuration file under the corresponding space , But without specifying the namespace configuration , The default configuration is public In the space , The way to specify the namespace is as follows :
# Corresponding to the created namespace ID, Here it corresponds to dev Namespace
cloud.nacos.config.namespace=483bb765-a42d-4112-90bc-50b8dff768b32.3、 Business isolation -Group grouping :
Group It can also realize the function of environmental isolation , but Group The main purpose of the design is to group different services in the same environment , Divide the configuration files of different microservices into the same group ,Nacos If you don't specify Group, The default grouping is DEFAULT_GROUP.
without Group, Just imagine this scene : There are two microservices , One is the order system , One is the user system , But they have the same configuration , such as datasource-url, So how to distinguish ? Now Group That comes in handy . The order system in the above scenario 、 The user system can be divided into a separate group , such as ORDER_GROUP、USER_GROUP, Of course, this is a fine-grained grouping , According to the business of the enterprise, multiple micro services can also be divided into a group .
Next, we will demonstrate how to specify grouping when creating configuration sets and when integrating , Or the previous example , The new configuration set is specified in the following location Group grouping :

The next in application.properties File grouping :
spring.cloud.nacos.config.namespace=483bb765-a42d-4112-90bc-50b8dff768b33、 Summary :
Nacos Implementing configuration management and dynamic configuration refresh is very simple , Summarize the following steps :
- ① Add corresponding spring-cloud-starter-alibaba-nacos-config rely on
- ② Use native annotations @Value() Import configuration
- ③ Use native annotations @RefreshScope Refresh configuration
- ④ Do a lot of environment configuration isolation according to your business scenario (Namespace)、 Different business configurations are isolated (Group)
4、 Shared configuration :
When we have more and more micro Services , There must be the same configuration , At this time, we can extract the same configuration as the common configuration of the project , For example, the data source information in the cluster 、 Log configuration information ,nacos It also supports the writing of multiple configuration sets in one configuration center .
(1) We are nacos New two in Data ID Namely db.yaml and log.yaml The file of .
(2) Add some configuration contents to the configuration file respectively
(3) stay Springboot Add the following nacos To configure :
spring:
cloud:
nacos:
config:
extension-configs[0]:
data-id: db.yaml
# The default is DEFAULT_GROUP
group: DEFAULT_GROUP
# Whether to refresh dynamically , The default is false
refresh: true
extension-configs[1]:
data-id: log.yaml
group: DEFAULT_GROUP
refresh: trueIn order to more clearly configure shared Data Id, Official recommendation shared-configs, The configuration is as follows :
spring:
cloud:
nacos:
config:
shared-configs[0]:
data-id: db.yaml
# The default is DEFAULT_GROUP
group: DEFAULT_GROUP
# Whether to refresh dynamically , The default is false
refresh: true
shared-configs[1]:
data-id: log.yaml
group: DEFAULT_GROUP
refresh: true(4) reflection : Here 2 The same configuration appears in files ,nacos How to choose ?
When more than one Data Id When the same configuration appears at the same time , Its priority relationship is spring.cloud.nacos.config.extension-configs[n].data-id among n The greater the value of , The higher the priority .
Be careful :spring.cloud.nacos.config.extension-configs[n].data-id The value of must have a file extension , The file extension can support properties, You can support yaml/yml. here spring.cloud.nacos.config.file-extension The configuration of the user-defined extension configuration Data Id File extensions have no effect .
(5) Configure load priority in different ways :
Nacos The configuration center currently provides the following three configuration capabilities from Nacos Pull the relevant configuration , When the three methods are used together , One of their priorities is :A < B < C:
- A: adopt spring.cloud.nacos.config.shared-configs[n].data-id Support multiple shares Data Id Configuration of
- B: adopt spring.cloud.nacos.config.extension-configs[n].data-id The way to support multiple extensions Data Id Configuration of
- C: Through internal rules (spring.cloud.nacos.config.prefix、spring.cloud.nacos.config.file-extension、spring.cloud.nacos.config.group) Automatically generate related Data Id To configure
Reference article :
SpringBoot2.X Integrate Nacos Do configuration center
Fifty five pictures show you the soul ferry of micro service Nacos How strong ?
边栏推荐
- 可视化yolov5格式数据集(labelme json文件)
- [camera topic] turn a drive to light up the camera
- How to find summer technical internship in junior year? Are you looking for a large company or a small company for technical internship?
- LabVIEW安装第三方VISA软件后NI VISA失效
- DQL basic operation
- Deep learning notes (constantly updating...)
- His experience in choosing a startup company or a big Internet company may give you some inspiration
- Cfdiv2 Fixed Point Guessing - (2 points for Interval answer)
- Socket programming
- 力扣(LeetCode)183. 从不订购的客户(2022.07.02)
猜你喜欢
![[Appendix 6 Application of reflection] Application of reflection: dynamic agent](/img/e7/0ee42902b178b13e9a41385267e7b6.jpg)
[Appendix 6 Application of reflection] Application of reflection: dynamic agent

In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?

小程序開發的部分功能

Redis: simple use of redis

Solution for processing overtime orders (Overtime unpaid)

Custom components, using NPM packages, global data sharing, subcontracting

The testing process that software testers should know

Certaines fonctionnalités du développement d'applets

Everything file search tool

《上市风云》荐书——唯勇气最可贵
随机推荐
Leetcode 183 Customers who never order (2022.07.02)
Redis: simple use of redis
NCTF 2018 part Title WP (1)
Recommendation letter of "listing situation" -- courage is the most valuable
ByteDance data Lake integration practice based on Hudi
技术大佬准备就绪,话题C位由你决定
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
Ni visa fails after LabVIEW installs the third-party visa software
使用Go语言实现try{}catch{}finally
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
In the face of difficult SQL requirements, HQL is not afraid
leetcode961. Find the elements repeated N times in the array with length 2n
[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
Iptables layer 4 forwarding
力扣(LeetCode)183. 从不订购的客户(2022.07.02)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance o
疫情当头,作为Leader如何进行团队的管理?| 社区征文
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
Learn BeanShell before you dare to say you know JMeter
Solution for processing overtime orders (Overtime unpaid)