2021-05-25 17:13:52

go注册服务到nacos

先引入nacos的sdk包到项目中,目前最新的是1.0.7版本

github.com/nacos-group/nacos-sdk-go v1.0.7

经过无数次的尝试,发现魔改后的nacos-spring 用go注册会提示重试三次都失败,失败内容如下:

call domain error:<request return error code 400> , result:<caused: Param 'serviceName' is required.;>

 

后来采用nacos docker搭建nacos注册中心可正常与spring项目通讯,至于加密通讯方面可能需要自己动手,先上go代码

nacos工具类:

package client

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/model"
	"github.com/nacos-group/nacos-sdk-go/vo"

	"strings"
)

type NacosClient struct {
	Client config_client.IConfigClient
	NamingClient naming_client.INamingClient
}
//创建nacos客户端
func NewNacos(option *Options,isJwt bool) *NacosClient {
	var clientConfig constant.ClientConfig
	if isJwt {
		clientConfig = constant.ClientConfig{
			TimeoutMs:      option.TimeoutMs,
			BeatInterval:   option.BeatInterval,
			LogDir:"/tmp/nacos/log",
			CacheDir:"/tmp/nacos/cache",
			LogLevel:"debug",
			//NamespaceId:"public",
			//AppName:"unknown",
			//OpenKMS:true,
			//Username:"nacos",
			//Password:"$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu",
			//AccessKey:"pigx",
			//SecretKey:"PBEWithMD5AndDES",
		}
	}else {
		clientConfig = constant.ClientConfig{
			TimeoutMs:      option.TimeoutMs,
			BeatInterval:   option.BeatInterval,
			LogDir:"/tmp/nacos/log",
			CacheDir:"/tmp/nacos/cache",
			LogLevel:"debug",
		}
	}


	serverConfigs := []constant.ServerConfig{
		*constant.NewServerConfig(
			option.Address,
			option.Port,
			constant.WithContextPath("/nacos")),
	}
	// Create Config Center
	client, err := clients.NewConfigClient(vo.NacosClientParam{
		ClientConfig:  &clientConfig,
		ServerConfigs: serverConfigs,
	})
	if err != nil {
		panic(err)
	}
	// Create Register Center
	namingClient,err:=clients.NewNamingClient(vo.NacosClientParam{
		ClientConfig:  &clientConfig,
		ServerConfigs: serverConfigs,
	})
	if err!=nil{
		panic(err)
	}
	return &NacosClient{Client: client,NamingClient: namingClient}
}
//项目公有配置
func (c *NacosClient) Publish(dataId, group, content string) bool {
	ok, err := c.Client.PublishConfig(vo.ConfigParam{
		DataId:  dataId,
		Group:   group,
		Content: content,
	})
	if err != nil {
		return false
	}
	return ok
}
//获取配置文件
func (c *NacosClient) Get(dataId, group string) string {
	s, err := c.Client.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
	})
	if err != nil {
		return ""
	}
	return s
}
//删除nacos配置
func (c *NacosClient) Delete(dataId, group string) bool {
	ok,err:=c.Client.DeleteConfig(vo.ConfigParam{
		DataId:   dataId,
		Group:    group,
	})
	if err!=nil{
		return false
	}
	return ok
}
//监听nacos配置文件变动
func (c *NacosClient) Listen(dataId, group string,OnChange func(namespace, group, dataId, data string)) error {
	return c.Client.ListenConfig(vo.ConfigParam{
		DataId:   dataId,
		Group:    group,
		OnChange: OnChange,
	})
}
//注册到nacos服务
func (c *NacosClient) Register(ip string,port uint64,name string) bool {
	ok,err:=c.NamingClient.RegisterInstance(vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: name,
		Weight:      1.0,
		//Metadata:	,
		GroupName:	"",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
	if err!=nil{
		fmt.Printf("注册失败:%v",err)
		return false
	}
	return ok
}
//注销nacos服务
func (c *NacosClient) Deregister(ip string,port uint64,name string) bool {
	ok ,err:=c.NamingClient.DeregisterInstance(vo.DeregisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: name,
		//Cluster:     "a",
		Ephemeral:   true,
	})
	if err!=nil{
		return false
	}
	return ok
}
//获取nacos服务信息
func (c *NacosClient) GetService(name string) (model.Service,error) {
	return c.NamingClient.GetService(vo.GetServiceParam{
		//Clusters:    []string{"a"},
		ServiceName: name,
	})
}
//获取一个健康的实例(加权随机轮询)
func (c *NacosClient) SelectOneHealthyInstance(name string) (*model.Instance,error) {
	return c.NamingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: name,
		//Clusters:    []string{"a"},
	})
}

实体

package client

type Options struct {
	TimeoutMs      uint64 //请求Nacos服务端的超时时间,默认是10000ms
	BeatInterval   int64  //发送到服务的心跳时间 默认5000ms
	Address        string //注册中心地址
	Port           uint64 //注册中心端口
}
func deafultOptions() *Options {
	return &Options{
		TimeoutMs:      10*1000,
		ListenInterval: 3*1000,
		BeatInterval:   5*1000,
	}
}
func (option *Options) WithAdress(address string) *Options {
	option.Address = address
	return option
}
func (option *Options) WithPort(port uint64) *Options {
	option.Port = port
	return option
}
func NewOption() *Options {
	return deafultOptions()
}

 

从nacos读取配置文件方法

option:=client.NewOption().WithAdress(nacosIp).WithPort(8848) //nacosIp 注册中心ip
nacosClient:=client.NewNacos(option,false)
content:=nacosClient.Get(global.GVA_DATA_ID,global.GVA_GROUP) //global.GVA_DATA_ID nacos中的配置文件明  global.GVA_GROUP分组

 

注册服务到注册中心方法

option:=client.NewOption().WithAdress(nacosIp).WithPort(port)  //注册中心和端口
nacosClient:=client.NewNacos(option,true)
if ok :=nacosClient.Register(localhostip,iport,serverName);ok{  //本机ip 本机端口  本服务名称
     //注册成功逻辑处理
}

 

 

本文链接:https://zk1006.com/archives/25.html

评论