golang使用 viper 加载 yaml 配置文件 并配合 Nacos 实现远程配置中心 自动侦测配置文件的修改

golang使用 viper  加载 yaml 配置文件 并配合 Nacos 实现远程配置中心


yaml配置:

host: '192.168.0.104'
port: 8848
user: 'nacos'
password: 'nacos'
namespace_id: '5248143c-0f12-4bf3-97dd-931bc42ad5dc'
dataid: 'order-srv'
group: 'dev'

Nacos配置:

{
"name": "order-srv",
"host": "192.168.0.102",
"port": 50054,
"mysql": {
"host": "192.168.0.104",
"port": 3306,
"database": "shop_order_srv",
"user": "root",
"pwd": "root"
},
"consul": {
"host": "192.168.0.104",
"port": 8500
},
"redis": {
"host": "192.168.0.104",
"port": 6379
},
"goods_srv": {
"name": "goods-srv"
},
"inventory_srv": {
"name": "inventory-srv"
},
"rocketmq": {
"host": "192.168.0.104",
"port": 9876
}
}

GO代码:

package initialize

import (
   "encoding/json"
   "fmt"
   "github.com/fsnotify/fsnotify"
   "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"
   "go.uber.org/zap"
   "shop_srvs/order_srv/global"
   "shop_srvs/order_srv/utils"
)

var isDebug bool

func InitConfig() {
   v := viper.New()

   configFileName := "order_srv/config-pro.yaml"

   isDebug = global.IsDebug()
   if isDebug {
      configFileName = "order_srv/config-dev.yaml"
   }
   v.SetConfigFile(configFileName)

   if err := v.ReadInConfig(); err != nil {
      zap.S().Error(err.Error())
      return
   }

   err := v.Unmarshal(global.Nacos)
   if err != nil {
      zap.S().Error(err.Error())
      return
   }

   zap.S().Infof("获取Nacos配置:%+v", global.Nacos)

   //动态监控配置文件是否更新
   v.WatchConfig()
   v.OnConfigChange(func(in fsnotify.Event) {
      zap.S().Infof("Nacos配置文件有更新:%s", in.Name)
      if err := v.ReadInConfig(); err != nil {
         zap.S().Error(err.Error())
         return
      }

      err := v.Unmarshal(global.Nacos)
      if err != nil {
         zap.S().Error(err.Error())
         return
      }

      zap.S().Infof("Nacos配置文件有更新:%+v", global.Nacos)
      initNacos()
   })
   initNacos()
}
func initNacos() {
   serverConfig := []constant.ServerConfig{
      {
         IpAddr: global.Nacos.Host,
         Port:   global.Nacos.Port,
      },
   }

   clientConfig := constant.ClientConfig{
      NamespaceId:         global.Nacos.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": serverConfig,
      "clientConfig":  clientConfig,
   })
   if err != nil {
      panic(err)
   }

   content, err := configClient.GetConfig(vo.ConfigParam{
      DataId: global.Nacos.DataId,
      Group:  global.Nacos.Group,
   })
   if err != nil {
      panic(err)
   }
   err = json.Unmarshal([]byte(content), &global.ServerConfig)
   fmt.Println(global.ServerConfig)
   if err != nil {
      zap.S().Panic(err.Error())
      return
   }
   if !isDebug {
      global.ServerConfig.Port, _ = utils.GetFreePort()
   }

   err = configClient.ListenConfig(vo.ConfigParam{
      DataId: global.Nacos.DataId,
      Group:  global.Nacos.Group,
      OnChange: func(namespace, group, dataId, data string) {
         fmt.Println("group:" + group + ", dataId:" + dataId)
         err = json.Unmarshal([]byte(data), &global.ServerConfig)
         if err != nil {
            zap.S().Errorf("nacos 更新配置时失败:%s", err.Error())
         }
         if !isDebug {
            global.ServerConfig.Port, _ = utils.GetFreePort()
         }
      },
   })
   if err != nil {
      panic(err)
   }
}

GO结构体设计:

package config

type Server struct {
   Name         string   `mapstructure:"name"`
   Host         string   `mapstructure:"host"`
   Port         int      `mapstructure:"port"`
   Mysql        Mysql    `mapstructure:"mysql"`
   Consul       Consul   `mapstructure:"consul"`
   Redis        Redis    `mapstructure:"redis"`
   GoodsSrv     Srv      `mapstructure:"goods_srv" json:"goods_srv"`
   InventorySrv Srv      `mapstructure:"inventory_srv" json:"inventory_srv"`
   Rocketmq     Rocketmq `mapstructure:"rocketmq_srv" json:"rocketmq"`
}
type Srv struct {
   Name string `mapstructure:"name"`
}

type Mysql struct {
   Host     string `mapstructure:"host"`
   Port     int    `mapstructure:"port"`
   Database string `mapstructure:"database"`
   User     string `mapstructure:"user"`
   Pwd      string `mapstructure:"pwd"`
}

type Consul struct {
   Host string `mapstructure:"host"`
   Port int    `mapstructure:"port"`
}
type Rocketmq struct {
   Host string `mapstructure:"host"`
   Port int    `mapstructure:"port"`
}

type Redis struct {
   Host string `mapstructure:"host"`
   Port int    `mapstructure:"port"`
}

type Nacos struct {
   Host        string `mapstructure:"host"`
   Port        uint64 `mapstructure:"port"`
   User        string `mapstructure:"user"`
   Password    string `mapstructure:"password"`
   NamespaceId string `mapstructure:"namespace_id"`
   DataId      string `mapstructure:"dataid"`
   Group       string `mapstructure:"group"`
}


最后编辑于:2022/03/01作者: 牛逼PHP

发表评论