init
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
package nacos
|
||||
|
||||
import (
|
||||
"github.com/nacos-group/nacos-sdk-go/v2/clients"
|
||||
"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
|
||||
"github.com/nacos-group/nacos-sdk-go/v2/model"
|
||||
"github.com/nacos-group/nacos-sdk-go/v2/vo"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var (
|
||||
cli naming_client.INamingClient
|
||||
groupName string
|
||||
)
|
||||
|
||||
// NewNacosRegistry 创建一个nacos注册中心
|
||||
func NewNacosRegistry() (*naming_client.INamingClient, error) {
|
||||
InitNacosRegistryConfig()
|
||||
if cli != nil {
|
||||
return &cli, nil
|
||||
}
|
||||
groupName = os.Getenv("NACOS_GROUP_NAME")
|
||||
var err error
|
||||
cli, err = clients.NewNamingClient(
|
||||
vo.NacosClientParam{
|
||||
ClientConfig: cc,
|
||||
ServerConfigs: sc,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cli, nil
|
||||
}
|
||||
|
||||
// RegisterService 注册当前服务到nacos中
|
||||
func RegisterService() error {
|
||||
client, err := NewNacosRegistry()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serviceName := os.Getenv("NACOS_SERVICE_NAME")
|
||||
host := os.Getenv("NACOS_SERVICE_HOST")
|
||||
port, err := strconv.Atoi(os.Getenv("NACOS_SERVICE_PORT"))
|
||||
if err != nil {
|
||||
port = 8848
|
||||
}
|
||||
weight, err := strconv.Atoi(os.Getenv("NACOS_SERVICE_WEIGHT"))
|
||||
if err != nil {
|
||||
weight = 10
|
||||
}
|
||||
_, err = (*client).RegisterInstance(vo.RegisterInstanceParam{
|
||||
Ip: host,
|
||||
Port: uint64(port),
|
||||
ServiceName: serviceName,
|
||||
Weight: float64(weight),
|
||||
Enable: true,
|
||||
Healthy: true,
|
||||
Ephemeral: false,
|
||||
GroupName: groupName,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DiscoverServiceList 发现服务列表
|
||||
func DiscoverServiceList(serviceName string) ([]model.Instance, error) {
|
||||
client, err := NewNacosRegistry()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
instances, err := (*client).SelectInstances(vo.SelectInstancesParam{
|
||||
ServiceName: serviceName,
|
||||
HealthyOnly: false,
|
||||
GroupName: groupName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
// DiscoverService 发现一个服务
|
||||
func DiscoverService(serviceName string) (model.Instance, error) {
|
||||
client, err := NewNacosRegistry()
|
||||
if err != nil {
|
||||
return model.Instance{}, err
|
||||
}
|
||||
instances, err := (*client).SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
|
||||
ServiceName: serviceName,
|
||||
GroupName: groupName,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Instance{}, err
|
||||
}
|
||||
return *instances, nil
|
||||
}
|
||||
Reference in New Issue
Block a user