不使用注册中心的话,可以使用viper,时时监控配置文件的变化,有变化就更新
go
package main
import (
"fmt"
"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"
"gopkg.in/yaml.v2"
)
type DatabaseNew struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Username string `yaml:"username"`
Dbname string `yaml:"dbname"`
Password string `yaml:"password"`
}
type ConfigNew struct {
Database DatabaseNew //数据库的配置
}
var GlobalConfig ConfigNew
func main() {
sc := []constant.ServerConfig{{
IpAddr: "127.0.0.1",
Port: 8848,
}}
cc := constant.ClientConfig{
NamespaceId: "xxxxx", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。
TimeoutMs: 3000, //超时
NotLoadCacheAtStart: true, //启动时
LogDir: "log",
CacheDir: "cache",
LogLevel: "debug",
}
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": sc,
"clientConfig": cc,
})
if err != nil {
fmt.Println(err.Error())
}
// DataId Group 是在可视化后台 自定义得
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "user",
Group: "prod",
})
SetConfig(content)
if err != nil {
fmt.Println(err.Error())
}
err = configClient.ListenConfig(vo.ConfigParam{
DataId: "user",
Group: "prod",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("配置文件发生了变化...")
fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
SetConfig(data)
},
})
ch := make(chan int)
ch <- 1
}
func SetConfig(content string) {
fmt.Println(content)
//或者使用viper
err := yaml.Unmarshal([]byte(content), &GlobalConfig)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%+v", GlobalConfig)
}