| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package main
- import (
- "fmt"
- "log"
- "strings"
- "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 = "127.0.0.1"
- nacosPort = 8848
- nacosDataId = "dev001"
- nacosGroup = "DEFAULT_GROUP"
- defaultConfig = viper.New()
- defaultConfig.SetConfigType("toml")
- //配置模型
- serverConfigs := []constant.ServerConfig{
- {
- IpAddr: nacosIp,
- Port: nacosPort,
- },
- }
- //客户端
- nacosClient, err := clients.NewConfigClient(
- vo.NacosClientParam{
- ClientConfig: &constant.ClientConfig{TimeoutMs: 5000,NamespaceId:"36a76206-1dec-4fb7-aa7f-dc49314e7963",LogLevel:"debug"},
- //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("server.port")
- fmt.Println("consul===", host)
- //time.Sleep(time.Second * 10)
- //}
- }
|