一、前言
nacos官网:https://github.com/nacos-group/nacos-sdk-go
对于nacos配置管理,通过Namespace、group、Data ID 能够定位一个配置集
- Namespace:代表不同环境。比如开发,测试,生产环境
- Group:代表某项目
- Data Id:每个项目下往往有若干个工程,每个配置集(Data Id)是一个工程的主配置文件
二、读取配置中心文件示例
1、本地启动nacos
startup.cmd -m standalone
2、增加配置
3、读取配置
package main
import (
"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() {
//clientconfig := constant.ClientConfig{
// //NamespaceId: "",
// //NotLoadCacheAtStart: true,
// //TimeoutMs: 5 * 1000,
//}
serverConfig := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
configClient, err := clients.CreateConfigClient(map[string]interface{}{
//"clientConfig": clientconfig,
"serverConfigs": serverConfig,
})
if err != nil {
fmt.Println("连接nacos")
}
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "nacos-simple-demo.yaml",
Group: "DEFAULT_GROUP",
})
fmt.Println("err:", err)
fmt.Println("content")
fmt.Println(content)
}
4、增加监听
package main
import (
"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"
"time"
)
func main() {
clientconfig := constant.ClientConfig{
NamespaceId: "a2fee285-6f06-4ddc-90e8-68367903f112",
NotLoadCacheAtStart: true,
TimeoutMs: 5 * 1000,
}
serverConfig := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"clientConfig": clientconfig,
"serverConfigs": serverConfig,
})
if err != nil {
fmt.Println("连接nacos")
}
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "nacos-simple-demo.yaml",
Group: "DEFAULT_GROUP",
})
fmt.Println("err:", err)
fmt.Println("content")
fmt.Println(content)
//增加监听配置
err = configClient.ListenConfig(vo.ConfigParam{
DataId: "nacos-simple-demo.yaml",
Group: "DEFAULT_GROUP",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("group:" + group + ",dataId:" + dataId + ",data:" + data)
},
})
if err != nil {
fmt.Println(err)
return
}
time.Sleep(time.Second * 60)
}