go读取nacos配置
作者:互联网
上文docker安装nacos我们已经安装了nacos,现在我们来看看如何读取配置文件。我们的nacos的示例采用和 go读取consul配置文件 一致:
go我这里采用 https://github.com/nacos-group/nacos-sdk-go 客户端, 直接上上代码:
package main import ( "fmt" "log" "strings" "time" "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" "github.com/spf13/viper" ) var ( defaultConfig *viper.Viper nacosIp string nacosPort uint64 nacosDataId string nacosGroup string ) func initConfig() *viper.Viper { nacosIp = "192.168.100.21" nacosPort = 8848 nacosDataId = "dev001" nacosGroup = "go" defaultConfig = viper.New() defaultConfig.SetConfigType("yaml") //配置模型 serverConfigs := []constant.ServerConfig{ {IpAddr: nacosIp, Port: nacosPort}, } //客户端 nacosClient, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: &constant.ClientConfig{TimeoutMs: 5000}, ServerConfigs: serverConfigs, }, ) if err != nil { log.Fatal("nacos初始化错误:", err) } content, err := nacosClient.GetConfig(vo.ConfigParam{DataId: nacosDataId, Group: nacosGroup}) if err != nil { log.Fatalln("nacos读取配置错误:" + content) } err = defaultConfig.ReadConfig(strings.NewReader(content)) if err != nil { log.Fatalln("Viper解析配置失败:", err) } go func() { time.Sleep(time.Second * 10) err = nacosClient.ListenConfig(vo.ConfigParam{ DataId: nacosDataId, Group: nacosGroup, OnChange: func(namespace, group, dataId, data string) { fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data) err = defaultConfig.ReadConfig(strings.NewReader(data)) if err != nil { log.Fatalln("Viper解析配置失败:", err) } }, }) }() return defaultConfig } func GetConfig() *viper.Viper { if defaultConfig == nil { defaultConfig = initConfig() } return defaultConfig } func main() { for { host := GetConfig().GetString("store.bicycle.color") fmt.Println("consul===", host) time.Sleep(time.Second * 10) } }
运行效果:
标签:group,读取,err,nacos,defaultConfig,viper,go 来源: https://www.cnblogs.com/majiang/p/14379335.html