聊聊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

原文 

https://segmentfault.com/a/1190000023028425

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 聊聊nacos-sdk-go的NamingProxy

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址