online_code/initialize/config.go
2022-05-25 18:51:57 +08:00

69 lines
2.0 KiB
Go
Raw 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 (
"git.echol.cn/loser/logger/log"
"online_code/config"
nr "git.echol.cn/loser/nacos-viper-remote"
"github.com/caarlos0/env/v6"
"github.com/fsnotify/fsnotify"
"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 == "" {
log.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 {
log.Panicf("%s", err)
}
vp.SetConfigType("yaml")
//尝试进行配置读取
if err = vp.ReadRemoteConfig(); err != nil {
log.Panic(err)
}
//异步监听Nacos中的配置变化如发生配置更改会直接同步到 viper实例中。
err = vp.WatchRemoteConfigOnChannel()
if err != nil {
log.Errorf("监听远程配置变动失败: %v", err)
}
// 解析配置文件为结构体
if err = vp.Unmarshal(&config.Scd); err != nil {
log.Panic(err)
}
vp.WatchConfig() // 监听配置文件变化
vp.OnConfigChange(func(e fsnotify.Event) {
log.Info("配置文件发生变动:", e.Name)
if err = vp.Unmarshal(&config.Scd); err != nil {
log.Panic(err)
}
// 配置文件发生变动,重新初始化一下连接信息
initClient()
})
}