Home > Article > Backend Development > An 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!