gateway/initialization/nacos.go

93 lines
2.4 KiB
Go
Raw Normal View History

2021-09-07 13:40:44 +08:00
package initialization
import (
2021-09-08 14:24:07 +08:00
"gateway/config"
2021-09-07 13:40:44 +08:00
"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"
)
// 初始化Nacos注册
func initNacos() {
2021-09-08 14:24:07 +08:00
config.InitNacosConfig()
2021-09-07 13:40:44 +08:00
sc := []constant.ServerConfig{
2021-09-08 14:24:07 +08:00
*constant.NewServerConfig(config.NacosConfig.Host, config.NacosConfig.Port),
2021-09-07 13:40:44 +08:00
}
cc := constant.ClientConfig{
2021-09-08 14:24:07 +08:00
AppName: config.AppInfo.AppName,
NamespaceId: config.NacosConfig.NamespaceId,
2021-09-07 13:40:44 +08:00
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]
}
2021-09-09 09:48:58 +08:00
success, err := client.RegisterInstance(vo.RegisterInstanceParam{
2021-09-07 13:40:44 +08:00
Ip: ip,
2021-09-08 14:24:07 +08:00
Port: config.AppInfo.Port,
2021-09-07 13:40:44 +08:00
Weight: 10,
Enable: true,
Healthy: true,
ServiceName: "gateway",
Ephemeral: true,
})
2021-09-07 17:12:29 +08:00
core.Log.Debug("Nacos注册结果: %v", success)
2021-09-07 13:40:44 +08:00
if !success {
2021-09-09 09:48:58 +08:00
core.Log.Panic("服务注册失败,退出程序: %v", err.Error())
2021-09-07 13:40:44 +08:00
}
2021-09-08 14:24:07 +08:00
// 打印所有服务
go func() {
instances, err := client.SelectAllInstances(vo.SelectAllInstancesParam{
ServiceName: config.AppInfo.AppName,
})
if err != nil {
core.Log.Error("获取所有服务失败")
return
}
core.Log.Debug("获取到服务总数: %v", len(instances))
for _, instance := range instances {
core.Log.Debug("服务ID %v --> %v:%v", instance.InstanceId, instance.Ip, instance.Port)
}
}()
2021-09-07 13:40:44 +08:00
configClient, err := clients.NewConfigClient(configParam)
if err != nil {
2021-09-07 17:12:29 +08:00
core.Log.Error("创建配置连接失败: %v", err.Error())
2021-09-07 13:40:44 +08:00
}
_ = configClient.ListenConfig(vo.ConfigParam{
2021-09-08 14:24:07 +08:00
DataId: config.NacosConfig.CenterConfigName,
2021-09-07 13:40:44 +08:00
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 {
2021-09-07 17:12:29 +08:00
core.Log.Panic("读取配置文件错误: %v", err.Error())
2021-09-07 13:40:44 +08:00
}
core.ConfigChanged(configStr)
}
func configChanged(namespace, group, dataId, data string) {
core.ConfigChanged(data)
}