go_gin_tmpl/initialize/config.go
2022-05-09 09:00:14 +08:00

68 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package initialize
import (
"ginDemo/config"
"gitee.ltd/lxh/logger"
"github.com/caarlos0/env/v6"
"github.com/fsnotify/fsnotify"
nr "github.com/lixh00/nacos-viper-remote"
"github.com/spf13/viper"
_ "github.com/spf13/viper/remote"
)
var vp *viper.Viper
// 初始化Nacos
func initNacos() {
// 初始化Nacos配置
if err := env.Parse(&config.Nacos); err != nil {
panic(err)
}
if config.Nacos.Host == "" {
logger.Say.Panic("Nacos配置错误")
}
}
// 初始化配置文件
func initConfig() {
vp = viper.New()
// 配置 Viper for Nacos 的远程仓库参数
nr.SetOptions(&nr.Option{
Url: config.Nacos.Host, // nacos server 多地址需要地址用;号隔开,如 Url: "loc1;loc2;loc3"
Port: config.Nacos.Port, // nacos server端口号
NamespaceId: config.Nacos.NamespaceId, // nacos namespace
GroupName: "DEFAULT_GROUP", // nacos group
Config: nr.Config{DataId: config.Nacos.CenterConfigName}, // nacos DataID
Auth: nil, // 如果需要验证登录,需要此参数
})
err := vp.AddRemoteProvider("nacos", config.Nacos.Host, "")
if err != nil {
logger.Say.Panicf("%s", err)
}
vp.SetConfigType("yaml")
//尝试进行配置读取
if err = vp.ReadRemoteConfig(); err != nil {
logger.Say.Panic(err)
}
//异步监听Nacos中的配置变化如发生配置更改会直接同步到 viper实例中。
err = vp.WatchRemoteConfigOnChannel()
if err != nil {
logger.Say.Errorf("监听远程配置变动失败: %v", err)
}
// 解析配置文件为结构体
if err = vp.Unmarshal(&config.Scd); err != nil {
logger.Say.Panic(err)
}
vp.WatchConfig() // 监听配置文件变化
vp.OnConfigChange(func(e fsnotify.Event) {
logger.Say.Info("配置文件发生变动:", e.Name)
if err = vp.Unmarshal(&config.Scd); err != nil {
logger.Say.Panic(err)
}
// 配置文件发生变动,重新初始化一下连接信息
initClient()
})
}