Backend Development
Golang
An article explaining in detail how to install and use the configuration center nacosAn article explaining in detail how to install and use the configuration center nacos
This article is introduced by the golang tutorial column to introduce you to the configuration center "nacos". Below, we will learn about the configuration center from the perspective of golang, the installation of naco and how to use nacos for configuration and read the configuration in nacos. Documents, etc. I hope it will be helpful to friends who need it!

What is the configuration center
A system used to uniformly manage all configurations in the project. Although it sounds simple, don't underestimate this module. If a medium-sized Internet project does not adopt the configuration center model, a large number of various configuration items, and various irregular modification requirements will definitely cause developers a lot of headaches and make management very confusing.
The service process of the configuration center is as follows: Users update configuration information in the configuration center. Service A and Service B receive configuration update notifications in a timely manner and obtain configurations from the configuration center. In general, the configuration center is a basic service component that uniformly manages various application configurations.
In the system architecture, the configuration center is a component in the entire microservice infrastructure system. Its function seems inconspicuous, it is nothing more than configuration management and access, but it is the entire microservice architecture. an indispensable part.
What is nacos
Nacos
Nacos is the abbreviation of Naming and Configuration Service. From the name, we can see the two areas it focuses on. It is Naming, which is the registration center and Configuration configuration center.
Business configuration, function switches, downgrading of weak dependencies in service management, and even database passwords may all use the dynamic configuration center. When there is no dedicated configuration center component, we use hard coding, configuration files, databases, caches, etc. to solve the problem. When modifying the configuration through hard coding, you need to recompile and package the configuration file, and the application needs to be restarted. The database performance is limited, and the cache loses timeliness.
Nacos configuration model
namespace group dataId uniquely determines a configuration
namespace: bound to the client, one clinet corresponds to one namespace, available To isolate the environment or differentiate tenants
group: group, differentiate business
dataId: configured id
Let’s see how it is used in actual scenarios
For example: an e-commerce website has these modules: user module, product module, order module, inventory module
This Several modules need to be configured and their configurations are different. This is how we make a namespace for each module. Each module needs to have
configuration during the development stage and configuration after going online. We use There are two groups of dev, and pro to distinguish. For dataId, whether it is dev or
pro, it must be filled in.
Installation of Nacos
Here we use docker directly for installation
Installation of Nacos (docker)
docker run --name nacos-standalone -e MODE=standalone -e JVM_XMS=512m -e JVM_XMX=512m -e JVM_XMN=256m -p 8848:8848 -d nacos/nacos-server:latest
Access: 192.168.1.103:8848/nacos/index.html Username/Password: nacos/nacos
Configuration startup:
docker container update --restart=always xxx
Use nacos for configuration
After nacos is successfully started, visit: 192.168.1.103:8848/nacos/index.html
You can create a namespace. We create a new user module user. After the creation is successful, you can see the corresponding id, for example: 7ae18f62-e2b9-48bd-bff2-a49e7443f5bc
Then we create a new configuration file under the user namespace and fill in the corresponding name (dataId) and group. Here we create a new josn configuration file :
{
"name": "user-web",
"host": "10.2.106.169",
"port": 9091,
"tags":["iceymoss", "goods", "golang", "web"],
"user_srv":{
"name": "user-srv",
"host": "10.2.106.169",
"port": 8081
},
"jwt":{
"key": "dfijdfjidhfjijdfbdfdFwohPd6XmVCdnQi"
},
"sms":{
"key": "mykey",
"secret": "mysecret"
},
"params":{
"sign_name": "生鲜小店",
"code": "SMS_244610581"
},
"redis":{
"host": "127.0.0.1",
"port": 6379,
"expir": 300
},
"verify":{
"width": 5
},
"consul":{
"host": "10.2.106.169",
"port": 8500
},
"tracing":{
"host": "127.0.0.1",
"port": 6831,
"name": "shopping"
}
}In this way, the entire configuration file is configured
Read the configuration file in nacos
Pull dependencies
We use go to read the configuration file and use the sdk that needs to pull nacos:
go get github.com/nacos-group/nacos-sdk-go/clients go get github.com/nacos-group/nacos-sdk-go/common/constant go get github.com/nacos-group/nacos-sdk-go/vo
Read the configuration
Before reading the configuration we First write a structure for configuration mapping
Directory structure:
nacos_test ├── config │ └── config.go └── main.go
When writing config, we need to pay attention to the fact that we need to keep the tag name consistent with the name in the configuration file
package config
//UserSerConfig 映射用户配置
type UserSerConfig struct {
Name string `mapstructure:"name" json:"name"`
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
}
//JWTConfig 映射token配置
type JWTConfig struct {
SigningKey string `mapstructure:"key" json:"key"`
}
//AliSmsConfig 阿里秘钥
type AliSmsConfig struct {
Apikey string `mapstructure:"key" json:"key"`
ApiSecret string `mapstructure:"secret" json:"secret"`
}
//ParamsConfig 短信模板配置
type ParamsConfig struct {
SignName string `mapstructure:"sign_name" json:"sign_name"`
TemplateCode string `mapstructure:"code" json:"code"`
}
//RedisConfig redis数据库配置
type RedisConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
Expir int `mapstructure:"expir" json:"expir"`
}
//Verifier 手机验证长度
type Verifier struct {
Width int `mapstructure:"width" json:"width"`
}
type ConsulConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
}
//ServerConfig 映射服务配置
type ServerConfig struct {
Name string `mapstructure:"name" json:"name"`
Port int `mapstructure:"port" json:"port"`
UserSerInfo UserSerConfig `mapstructure:"user_srv" json:"user_srv"`
JWTInfo JWTConfig `mapstructure:"jwt" json:"jwt"`
AliSms AliSmsConfig `mapstructure:"sms" json:"sms"`
Params ParamsConfig `mapstructure:"params" json:"params"`
Redis RedisConfig `mapstructure:"redis" json:"redis"`
Verify Verifier `mapstructure:"verify" json:"verify"`
ConsulInfo ConsulConfig `mapstructure:"consul" json:"consul"`
}Read the configuration file below:
package main
import (
"StudyGin/nacos/config"
"encoding/json"
"fmt"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
)
func main() {
//服务端配置, nacos运行的socket
sc := []constant.ServerConfig{
{
IpAddr: "10.2.81.102",
Port: 8848,
},
}
//客服端配置
cc := constant.ClientConfig{
NamespaceId: "7ae18f62-e2b9-48bd-bff2-a49e7443f5bc", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "tmp/nacos/log",
CacheDir: "tmp/nacos/cache",
//RotateTime: "1h",
//MaxAge: 3,
LogLevel: "debug",
}
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": sc,
"clientConfig": cc,
})
if err != nil {
panic(err)
}
//获取配置
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "user-web.json",
Group: "dev"})
if err != nil {
panic(err)
}
Config := &config.ServerConfig{}
//将配置信息读取到config.ServerConfig{}对象中
err = json.Unmarshal([]byte(content), &Config)
if err != nil {
panic(err)
}
fmt.Println(Config)
}Output:
&{user-web 9091 {user-srv 10.2.106.169 8081} {dfijdfjidhfjijdfbdfdFwohPd6XmVCdnQi} {mykey mysecret} {生鲜小店 SMS_244610581} {127.0.0.1 6379 300} {5} {10.2.106.1600}}Of course, both the configuration center and viper provide real-time monitoring configuration
You can write it like this:
//监听配置变化
err = configClient.ListenConfig(vo.ConfigParam{
DataId: "user-web",
Group: "DEV",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("配置文件变化")
fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
},
})
time.Sleep(3000 * time.Second)The above is the detailed content of An article explaining in detail how to install and use the configuration center nacos. For more information, please follow other related articles on the PHP Chinese website!
Golang vs. Python: Concurrency and MultithreadingApr 17, 2025 am 12:20 AMGolang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.
Golang and C : The Trade-offs in PerformanceApr 17, 2025 am 12:18 AMThe performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
Golang vs. Python: Applications and Use CasesApr 17, 2025 am 12:17 AMChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.
Golang vs. Python: Key Differences and SimilaritiesApr 17, 2025 am 12:15 AMGolang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.
Golang vs. Python: Ease of Use and Learning CurveApr 17, 2025 am 12:12 AMIn what aspects are Golang and Python easier to use and have a smoother learning curve? Golang is more suitable for high concurrency and high performance needs, and the learning curve is relatively gentle for developers with C language background. Python is more suitable for data science and rapid prototyping, and the learning curve is very smooth for beginners.
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function





