gateway/initialization/nacos.go
2021-09-07 13:40:44 +08:00

77 lines
1.8 KiB
Go

package initialization
import (
"gateway/core"
"gateway/utils"
"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"
"log"
)
// 初始化Nacos注册
func initNacos() {
sc := []constant.ServerConfig{
*constant.NewServerConfig("192.168.0.124", 8848),
}
cc := constant.ClientConfig{
AppName: "gateway",
//NamespaceId: "e56f939e-6d22-449c-97d2-39a8ae5afd58", //namespace id
NamespaceId: "",
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
configParam := vo.NacosClientParam{
ClientConfig: &cc,
ServerConfigs: sc,
}
client, err := clients.NewNamingClient(configParam)
if err != nil {
panic(err)
}
ip := "gateway"
if ips := utils.GetIps(); ips != nil {
ip = ips[0]
}
success, _ := client.RegisterInstance(vo.RegisterInstanceParam{
Ip: ip,
Port: 8889,
Weight: 10,
Enable: true,
Healthy: true,
ServiceName: "gateway",
Ephemeral: true,
})
log.Println("Nacos注册结果: ", success)
if !success {
log.Fatal("服务注册失败,退出程序")
}
configClient, err := clients.NewConfigClient(configParam)
if err != nil {
log.Fatalf("创建配置连接失败: %v", err.Error())
}
_ = configClient.ListenConfig(vo.ConfigParam{
DataId: "gateway.yml",
Group: "DEFAULT_GROUP",
OnChange: configChanged,
})
// 读取初始配置
core.NacosClient = core.NewNacosClient(client, configClient)
configStr, err := configClient.GetConfig(vo.ConfigParam{DataId: "gateway.yml", Group: "DEFAULT_GROUP"})
if err != nil {
log.Panicf("读取配置文件错误: %v", err.Error())
}
core.ConfigChanged(configStr)
}
func configChanged(namespace, group, dataId, data string) {
core.ConfigChanged(data)
}