Go教程

聊聊nacos-sdk-go的NamingProxy

本文主要是介绍聊聊nacos-sdk-go的NamingProxy,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文主要研究一下nacos-sdk-go的NamingProxy

NamingProxy

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

type NamingProxy struct {
	clientConfig constant.ClientConfig
	nacosServer  nacos_server.NacosServer
}
复制代码
  • NamingProxy定义了clientConfig、nacosServer属性

NewNamingProxy

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func NewNamingProxy(clientCfg constant.ClientConfig, serverCfgs []constant.ServerConfig, httpAgent http_agent.IHttpAgent) (NamingProxy, error) {
	srvProxy := NamingProxy{}
	srvProxy.clientConfig = clientCfg

	var err error
	srvProxy.nacosServer, err = nacos_server.NewNacosServer(serverCfgs, clientCfg, httpAgent, clientCfg.TimeoutMs, clientCfg.Endpoint)
	if err != nil {
		return srvProxy, err
	}

	return srvProxy, nil
}
复制代码
  • NewNamingProxy通过nacos_server.NewNacosServer创建srvProxy.nacosServer

RegisterInstance

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) RegisterInstance(serviceName string, groupName string, instance model.Instance) (string, error) {
	log.Printf("[INFO] register instance namespaceId:<%s>,serviceName:<%s> with instance:<%s> \n", proxy.clientConfig.NamespaceId, serviceName, utils.ToJsonString(instance))
	params := map[string]string{}
	params["namespaceId"] = proxy.clientConfig.NamespaceId
	params["serviceName"] = serviceName
	params["groupName"] = groupName
	params["clusterName"] = instance.ClusterName
	params["ip"] = instance.Ip
	params["port"] = strconv.Itoa(int(instance.Port))
	params["weight"] = strconv.FormatFloat(instance.Weight, 'f', -1, 64)
	params["enable"] = strconv.FormatBool(instance.Enable)
	params["healthy"] = strconv.FormatBool(instance.Healthy)
	params["metadata"] = utils.ToJsonString(instance.Metadata)
	params["ephemeral"] = strconv.FormatBool(instance.Ephemeral)
	return proxy.nacosServer.ReqApi(constant.SERVICE_PATH, params, http.MethodPost)
}
复制代码
  • RegisterInstance构造params,然后通过proxy.nacosServer.ReqApi(constant.SERVICE_PATH, params, http.MethodPost)发送POST请求

DeregisterInstance

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) DeregisterInstance(serviceName string, ip string, port uint64, clusterName string, ephemeral bool) (string, error) {
	log.Printf("[INFO] deregister instance namespaceId:<%s>,serviceName:<%s> with instance:<%s:%d@%s> \n", proxy.clientConfig.NamespaceId, serviceName, ip, port, clusterName)
	params := map[string]string{}
	params["namespaceId"] = proxy.clientConfig.NamespaceId
	params["serviceName"] = serviceName
	params["clusterName"] = clusterName
	params["ip"] = ip
	params["port"] = strconv.Itoa(int(port))
	params["ephemeral"] = strconv.FormatBool(ephemeral)
	return proxy.nacosServer.ReqApi(constant.SERVICE_PATH, params, http.MethodDelete)
}
复制代码
  • DeregisterInstance方法构造params,然后通过proxy.nacosServer.ReqApi(constant.SERVICE_PATH, params, http.MethodDelete)发送DELETE请求

SendBeat

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) SendBeat(info model.BeatInfo) (int64, error) {
	log.Printf("[INFO] namespaceId:<%s> sending beat to server:<%s> \n", proxy.clientConfig.NamespaceId, utils.ToJsonString(info))
	params := map[string]string{}
	params["namespaceId"] = proxy.clientConfig.NamespaceId
	params["serviceName"] = info.ServiceName
	params["beat"] = utils.ToJsonString(info)
	api := constant.SERVICE_BASE_PATH + "/instance/beat"
	result, err := proxy.nacosServer.ReqApi(api, params, http.MethodPut)
	if err != nil {
		return 0, err
	}
	if result != "" {
		interVal, err := jsonparser.GetInt([]byte(result), "clientBeatInterval")
		if err != nil {
			return 0, errors.New(fmt.Sprintf("[ERROR] namespaceId:<%s> sending beat to server:<%s> get 'clientBeatInterval' from <%s> error:<%s>", proxy.clientConfig.NamespaceId, utils.ToJsonString(info), result, err.Error()))
		} else {
			return interVal, nil
		}
	}
	return 0, nil

}
复制代码
  • SendBeat方法通过proxy.nacosServer.ReqApi(api, params, http.MethodPut)发送PUT请求

GetServiceList

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) GetServiceList(pageNo int, pageSize int, groupName string, selector *model.ExpressionSelector) (*model.ServiceList, error) {
	params := map[string]string{}
	params["namespaceId"] = proxy.clientConfig.NamespaceId
	params["groupName"] = groupName
	params["pageNo"] = strconv.Itoa(pageNo)
	params["pageSize"] = strconv.Itoa(pageSize)

	if selector != nil {
		switch selector.Type {
		case "label":
			params["selector"] = utils.ToJsonString(selector)
			break
		default:
			break

		}
	}

	api := constant.SERVICE_BASE_PATH + "/service/list"
	result, err := proxy.nacosServer.ReqApi(api, params, http.MethodGet)
	if err != nil {
		return nil, err
	}
	if result == "" {
		return nil, errors.New("request server return empty")
	}

	serviceList := model.ServiceList{}
	count, err := jsonparser.GetInt([]byte(result), "count")
	if err != nil {
		return nil, errors.New(fmt.Sprintf("[ERROR] namespaceId:<%s> get service list pageNo:<%d> pageSize:<%d> selector:<%s> from <%s> get 'count' from <%s> error:<%s>", proxy.clientConfig.NamespaceId, pageNo, pageSize, utils.ToJsonString(selector), groupName, result, err.Error()))
	}
	var doms []string
	_, err = jsonparser.ArrayEach([]byte(result), func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
		doms = append(doms, string(value))
	}, "doms")
	if err != nil {
		return nil, errors.New(fmt.Sprintf("[ERROR] namespaceId:<%s> get service list pageNo:<%d> pageSize:<%d> selector:<%s> from <%s> get 'doms' from <%s> error:<%s> ", proxy.clientConfig.NamespaceId, pageNo, pageSize, utils.ToJsonString(selector), groupName, result, err.Error()))
	}
	serviceList.Count = count
	serviceList.Doms = doms
	return &serviceList, nil
}
复制代码
  • GetServiceList方法通过proxy.nacosServer.ReqApi(api, params, http.MethodGet)发送GET请求,然后解析为serviceList

ServerHealthy

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) ServerHealthy() bool {
	api := constant.SERVICE_BASE_PATH + "/operator/metrics"
	result, err := proxy.nacosServer.ReqApi(api, map[string]string{}, http.MethodGet)
	if err != nil {
		log.Printf("[ERROR]:namespaceId:[%s] sending server healthy failed!,result:%s error:%s", proxy.clientConfig.NamespaceId, result, err.Error())
		return false
	}
	if result != "" {
		status, err := jsonparser.GetString([]byte(result), "status")
		if err != nil {
			log.Printf("[ERROR]:namespaceId:[%s] sending server healthy failed!,result:%s error:%s", proxy.clientConfig.NamespaceId, result, err.Error())
		} else {
			return status == "UP"
		}
	}
	return false
}
复制代码
  • ServerHealthy方法请求/operator/metrics判断是否healthy

QueryList

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) QueryList(serviceName string, clusters string, udpPort int, healthyOnly bool) (string, error) {
	param := make(map[string]string)
	param["namespaceId"] = proxy.clientConfig.NamespaceId
	param["serviceName"] = serviceName
	param["clusters"] = clusters
	param["udpPort"] = strconv.Itoa(udpPort)
	param["healthyOnly"] = strconv.FormatBool(healthyOnly)
	param["clientIp"] = utils.LocalIP()
	api := constant.SERVICE_PATH + "/list"
	return proxy.nacosServer.ReqApi(api, param, http.MethodGet)
}
复制代码
  • QueryList方法请求`/list获取服务列表

GetAllServiceInfoList

nacos-sdk-go-v0.3.2/clients/naming_client/naming_proxy.go

func (proxy *NamingProxy) GetAllServiceInfoList(namespace string, groupName string, clusters string) (string, error) {
	param := make(map[string]string)
	param["namespaceId"] = proxy.clientConfig.NamespaceId
	param["clusters"] = clusters
	param["groupName"] = groupName
	api := constant.SERVICE_INFO_PATH + "/getAll"
	return proxy.nacosServer.ReqApi(api, param, http.MethodGet)
}
复制代码
  • GetAllServiceInfoList方法请求/getAll获取所有服务列表

小结

NamingProxy定义了clientConfig、nacosServer属性;它提供了NewNamingProxy、RegisterInstance、DeregisterInstance、SendBeat、GetServiceList、ServerHealthy、QueryList、GetAllServiceInfoList方法

doc

  • naming_proxy
这篇关于聊聊nacos-sdk-go的NamingProxy的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!