93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
package initialization
|
||
|
||
import (
|
||
"gateway/config"
|
||
"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() {
|
||
config.InitNacosConfig()
|
||
|
||
sc := []constant.ServerConfig{
|
||
*constant.NewServerConfig(config.NacosConfig.Host, config.NacosConfig.Port),
|
||
}
|
||
cc := constant.ClientConfig{
|
||
AppName: config.AppInfo.AppName,
|
||
NamespaceId: config.NacosConfig.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, err := client.RegisterInstance(vo.RegisterInstanceParam{
|
||
Ip: ip,
|
||
Port: config.AppInfo.Port,
|
||
Weight: 10,
|
||
Enable: true,
|
||
Healthy: true,
|
||
ServiceName: "gateway",
|
||
Ephemeral: true,
|
||
})
|
||
core.Log.Debug("Nacos注册结果: %v", success)
|
||
if !success {
|
||
core.Log.Panic("服务注册失败,退出程序: %v", err.Error())
|
||
}
|
||
|
||
// 打印所有服务
|
||
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)
|
||
}
|
||
}()
|
||
|
||
configClient, err := clients.NewConfigClient(configParam)
|
||
if err != nil {
|
||
core.Log.Error("创建配置连接失败: %v", err.Error())
|
||
}
|
||
_ = configClient.ListenConfig(vo.ConfigParam{
|
||
DataId: config.NacosConfig.CenterConfigName,
|
||
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 {
|
||
core.Log.Panic("读取配置文件错误: %v", err.Error())
|
||
}
|
||
core.ConfigChanged(configStr)
|
||
}
|
||
|
||
func configChanged(namespace, group, dataId, data string) {
|
||
core.ConfigChanged(data)
|
||
}
|