前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >聊聊nacos-sdk-go的NacosServer

聊聊nacos-sdk-go的NacosServer

作者头像
code4it
发布2020-07-02 14:15:11
3170
发布2020-07-02 14:15:11
举报
文章被收录于专栏:码匠的流水账

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

NacosServer

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
type NacosServer struct {
    sync.RWMutex
    securityLogin       security.AuthClient
    serverList          []constant.ServerConfig
    httpAgent           http_agent.IHttpAgent
    timeoutMs           uint64
    endpoint            string
    lastSrvRefTime      int64
    vipSrvRefInterMills int64
}
  • NacosServer定义了securityLogin、serverList、httpAgent、timeoutMs、endpoint、lastSrvRefTime、vipSrvRefInterMills属性

NewNacosServer

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func NewNacosServer(serverList []constant.ServerConfig, clientCfg constant.ClientConfig, httpAgent http_agent.IHttpAgent, timeoutMs uint64, endpoint string) (NacosServer, error) {
    if len(serverList) == 0 && endpoint == "" {
        return NacosServer{}, errors.New("both serverlist  and  endpoint are empty")
    }

    securityLogin := security.NewAuthClient(clientCfg, serverList, httpAgent)

    ns := NacosServer{
        serverList:          serverList,
        securityLogin:       securityLogin,
        httpAgent:           httpAgent,
        timeoutMs:           timeoutMs,
        endpoint:            endpoint,
        vipSrvRefInterMills: 10000,
    }
    ns.initRefreshSrvIfNeed()
    _, err := securityLogin.Login()

    if err != nil {
        return ns, err
    }

    securityLogin.AutoRefresh()
    return ns, nil
}
  • NewNacosServer创建NacosServer及securityLogin,然后执行securityLogin.AutoRefresh()

callConfigServer

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) callConfigServer(api string, params map[string]string, newHeaders map[string]string,
    method string, curServer string, contextPath string, timeoutMS uint64) (result string, err error) {
    if contextPath == "" {
        contextPath = constant.WEB_CONTEXT
    }

    signHeaders := getSignHeaders(params, newHeaders)

    url := "http://" + curServer + contextPath + api
    headers := map[string][]string{}
    for k, v := range newHeaders {
        if k != "accessKey" && k != "secretKey" {
            headers[k] = []string{v}
        }
    }
    headers["Client-Version"] = []string{constant.CLIENT_VERSION}
    headers["User-Agent"] = []string{constant.CLIENT_VERSION}
    //headers["Accept-Encoding"] = []string{"gzip,deflate,sdch"}
    headers["Connection"] = []string{"Keep-Alive"}
    headers["exConfigInfo"] = []string{"true"}
    uid, err := uuid.NewV4()
    if err != nil {
        return
    }
    headers["RequestId"] = []string{uid.String()}
    headers["Request-Module"] = []string{"Naming"}
    headers["Content-Type"] = []string{"application/x-www-form-urlencoded;charset=utf-8"}
    headers["Spas-AccessKey"] = []string{newHeaders["accessKey"]}
    headers["Timestamp"] = []string{signHeaders["timeStamp"]}
    headers["Spas-Signature"] = []string{signHeaders["Spas-Signature"]}
    injectSecurityInfo(server, params)

    var response *http.Response
    response, err = server.httpAgent.Request(method, url, headers, timeoutMS, params)
    if err != nil {
        return
    }
    var bytes []byte
    bytes, err = ioutil.ReadAll(response.Body)
    defer response.Body.Close()
    if err != nil {
        return
    }
    result = string(bytes)
    if response.StatusCode == 200 {
        return
    } else {
        err = nacos_error.NewNacosError(strconv.Itoa(response.StatusCode), string(bytes), nil)
        return
    }
}
  • callConfigServer方法通过injectSecurityInfo注入SecurityInfo,然后通过server.httpAgent.Request(method, url, headers, timeoutMS, params)执行请求

callServer

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) callServer(api string, params map[string]string, method string, curServer string, contextPath string) (result string, err error) {
    if contextPath == "" {
        contextPath = constant.WEB_CONTEXT
    }

    url := "http://" + curServer + contextPath + api
    headers := map[string][]string{}
    headers["Client-Version"] = []string{constant.CLIENT_VERSION}
    headers["User-Agent"] = []string{constant.CLIENT_VERSION}
    //headers["Accept-Encoding"] = []string{"gzip,deflate,sdch"}
    headers["Connection"] = []string{"Keep-Alive"}
    uid, err := uuid.NewV4()
    if err != nil {
        return
    }
    headers["RequestId"] = []string{uid.String()}
    headers["Request-Module"] = []string{"Naming"}
    headers["Content-Type"] = []string{"application/x-www-form-urlencoded;charset=utf-8"}

    injectSecurityInfo(server, params)

    var response *http.Response
    response, err = server.httpAgent.Request(method, url, headers, server.timeoutMs, params)
    if err != nil {
        return
    }
    var bytes []byte
    bytes, err = ioutil.ReadAll(response.Body)
    defer response.Body.Close()
    if err != nil {
        return
    }
    result = string(bytes)
    if response.StatusCode == 200 {
        return
    } else {
        err = errors.New(fmt.Sprintf("request return error code %d", response.StatusCode))
        return
    }
}
  • callServer方法通过injectSecurityInfo注入SecurityInfo,通过server.httpAgent.Request(method, url, headers, server.timeoutMs, params)执行请求

ReqConfigApi

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) ReqConfigApi(api string, params map[string]string, headers map[string]string, method string, timeoutMS uint64) (string, error) {
    srvs := server.serverList
    if srvs == nil || len(srvs) == 0 {
        return "", errors.New("server list is empty")
    }

    injectSecurityInfo(server, params)

    //only one server,retry request when error
    var err error
    var result string
    if len(srvs) == 1 {
        for i := 0; i < constant.REQUEST_DOMAIN_RETRY_TIME; i++ {
            result, err = server.callConfigServer(api, params, headers, method, getAddress(srvs[0]), srvs[0].ContextPath, timeoutMS)
            if err == nil {
                return result, nil
            }
            log.Printf("[ERROR] api<%s>,method:<%s>, params:<%s>, call domain error:<%s> , result:<%s> \n", api, method, utils.ToJsonString(params), err.Error(), result)
        }
        return "", err
    } else {
        index := rand.Intn(len(srvs))
        for i := 1; i <= len(srvs); i++ {
            curServer := srvs[index]
            result, err = server.callConfigServer(api, params, headers, method, getAddress(curServer), curServer.ContextPath, timeoutMS)
            if err == nil {
                return result, nil
            }
            log.Printf("[ERROR] api<%s>,method:<%s>, params:<%s>, call domain error:<%s> , result:<%s> \n", api, method, utils.ToJsonString(params), err.Error(), result)
            index = (index + i) % len(srvs)
        }
        return "", err
    }
}
  • ReqConfigApi方法通过injectSecurityInfo注入SecurityInfo,通过server.callConfigServer执行请求,对于srvs有多个地址的则随机选择一个index执行,执行失败则切换下一个

ReqApi

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) ReqApi(api string, params map[string]string, method string) (string, error) {
    srvs := server.serverList
    if srvs == nil || len(srvs) == 0 {
        return "", errors.New("server list is empty")
    }

    injectSecurityInfo(server, params)

    //only one server,retry request when error
    if len(srvs) == 1 {
        for i := 0; i < constant.REQUEST_DOMAIN_RETRY_TIME; i++ {
            result, err := server.callServer(api, params, method, getAddress(srvs[0]), srvs[0].ContextPath)
            if err == nil {
                return result, nil
            }
            log.Printf("[ERROR] api<%s>,method:<%s>, params:<%s>, call domain error:<%s> , result:<%s> \n", api, method, utils.ToJsonString(params), err.Error(), result)
        }
        return "", errors.New("retry " + strconv.Itoa(constant.REQUEST_DOMAIN_RETRY_TIME) + " times request failed!")
    } else {
        index := rand.Intn(len(srvs))
        for i := 1; i <= len(srvs); i++ {
            curServer := srvs[index]
            result, err := server.callServer(api, params, method, getAddress(curServer), curServer.ContextPath)
            if err == nil {
                return result, nil
            }
            log.Printf("[ERROR] api<%s>,method:<%s>, params:<%s>, call domain error:<%s> , result:<%s> \n", api, method, utils.ToJsonString(params), err.Error(), result)
            index = (index + i) % len(srvs)
        }
        return "", errors.New("retry " + strconv.Itoa(constant.REQUEST_DOMAIN_RETRY_TIME) + " times request failed!")
    }
}
  • ReqApi方法通过injectSecurityInfo注入SecurityInfo,通过server.callConfigServer执行请求,对于srvs有多个地址的则随机选择一个index执行,执行失败则切换下一个

initRefreshSrvIfNeed

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) initRefreshSrvIfNeed() {
    if server.endpoint == "" {
        return
    }
    server.refreshServerSrvIfNeed()
    go func() {
        time.Sleep(time.Duration(1) * time.Second)
        server.refreshServerSrvIfNeed()
    }()

}
  • initRefreshSrvIfNeed方法执行server.refreshServerSrvIfNeed(),然后异步执行server.refreshServerSrvIfNeed()

refreshServerSrvIfNeed

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) refreshServerSrvIfNeed() {
    if utils.CurrentMillis()-server.lastSrvRefTime < server.vipSrvRefInterMills && len(server.serverList) > 0 {
        return
    }

    var list []string
    urlString := "http://" + server.endpoint + "/nacos/serverlist"
    result := server.httpAgent.RequestOnlyResult(http.MethodGet, urlString, nil, server.timeoutMs, nil)
    list = strings.Split(result, "\n")
    log.Printf("[info] http nacos server list: <%s> \n", result)

    var servers []constant.ServerConfig
    for _, line := range list {
        if line != "" {
            splitLine := strings.Split(strings.TrimSpace(line), ":")
            port := 8848
            var err error
            if len(splitLine) == 2 {
                port, err = strconv.Atoi(splitLine[1])
                if err != nil {
                    log.Printf("[ERROR] get port from server:<%s>  error: <%s> \n", line, err.Error())
                    continue
                }
            }
            servers = append(servers, constant.ServerConfig{IpAddr: splitLine[0], Port: uint64(port), ContextPath: constant.WEB_CONTEXT})
        }
    }
    if len(servers) > 0 {
        if !reflect.DeepEqual(server.serverList, servers) {
            server.Lock()
            log.Printf("[info] server list is updated, old: <%v>,new:<%v> \n", server.serverList, servers)
            server.serverList = servers
            server.lastSrvRefTime = utils.CurrentMillis()
            server.Unlock()
        }

    }

    return
}
  • refreshServerSrvIfNeed方法判断距离server.lastSrvRefTime是否超过server.vipSrvRefInterMills,超过则执行请求获取serverlist,然后判断serverList是否变更,变更的话则更新serverList及lastSrvRefTime

GetServerList

nacos-sdk-go-v0.3.2/common/nacos_server/nacos_server.go

代码语言:javascript
复制
func (server *NacosServer) GetServerList() []constant.ServerConfig {
    return server.serverList
}
  • GetServerList方法直接返回server.serverList

小结

NacosServer定义了securityLogin、serverList、httpAgent、timeoutMs、endpoint、lastSrvRefTime、vipSrvRefInterMills属性;它提供了NewNacosServer、ReqConfigApi、ReqApi、GetServerList等方法

doc

  • nacos_server
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码匠的流水账 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NacosServer
  • NewNacosServer
  • callConfigServer
  • callServer
  • ReqConfigApi
  • ReqApi
  • initRefreshSrvIfNeed
  • refreshServerSrvIfNeed
  • GetServerList
  • 小结
  • doc
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档