不使用注册中心的话,可以使用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",
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())
}
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)
err := yaml.Unmarshal([]byte(content), &GlobalConfig)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%+v", GlobalConfig)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2023-11-07 Golang简单使用wasm
2023-11-07 Go使用minio
2023-11-07 Go-zero对接dtm
2023-11-07 Golang实现简单的后门程序