package main
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/clients/config_client"
"gopkg.in/yaml.v3"
"log"
"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"
)
const (
NacosnamespaceId = "c0c576b7-1d60-48e9-9b2f-8d440d68c19b"
Nacosuser = "nacos"
Nacospassword = "nacos"
NacosdataId = "my.yaml"
Nacosgroup = "DEFAULT_GROUP"
)
type AppConfig struct {
Title string `yaml:"title"`
Version string `yaml:"version"`
}
type Config struct {
App AppConfig `yaml:"app"`
}
var (
sc = []constant.ServerConfig{
{
IpAddr: "192.168.40.180",
Port: 8848,
}, {
IpAddr: "192.168.40.180",
Port: 8848},
{
IpAddr: "192.168.40.180",
Port: 8848},
}
GlobalConfig Config
)
func main() {
// 获取初始配置
err := getConfig()
if err != nil {
log.Fatalln(err)
}
// 保持程序运行
select {}
}
// 初始化nacos客户端
func initNacosClient() (configClient config_client.IConfigClient, err error) {
cc := constant.ClientConfig{
NamespaceId: NacosnamespaceId, // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。
TimeoutMs: 1000,
NotLoadCacheAtStart: true,
Username: Nacosuser,
Password: Nacospassword,
}
configClient, err = clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": sc,
"clientConfig": cc,
})
if err != nil {
return nil, err
}
return configClient, nil
}
// 获取初始配置
func getFirstConfig() (config Config, err error) {
configClient, _ := initNacosClient()
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: NacosdataId,
Group: Nacosgroup,
})
if err != nil {
log.Fatal(err.Error())
}
var firstConfig Config
err = yaml.Unmarshal([]byte(content), &firstConfig)
if err != nil {
return Config{}, err
}
fmt.Println("初始化配置:", firstConfig)
return firstConfig, nil
}
// 动态监听配置
func getConfig() (err error) {
configClient, _ := initNacosClient()
GlobalConfig, _ = getFirstConfig()
var newConfig Config
err = configClient.ListenConfig(vo.ConfigParam{
DataId: NacosdataId,
Group: Nacosgroup,
OnChange: func(NacosnamespaceId, Nacosgroup, NacosdataId, data string) {
err := yaml.Unmarshal([]byte(data), &newConfig)
if err != nil {
log.Println("解析新配置失败:", err)
}
if newConfig != GlobalConfig {
log.Println("配置已更新:", newConfig)
GlobalConfig = newConfig // 更新为新的配置
}
},
})
if err != nil {
return err
}
return nil
}
go-nacos 初始化、动态获取配置
于 2024-09-04 11:10:35 首次发布