聊聊nacos-coredns-plugin的ServerMan

2021-02-26  本文已影响0人  go4it

本文主要研究一下nacos-coredns-plugin的ServerManager

ServerManager

nacos-coredns-plugin/nacos/server_manager.go

type ServerManager struct {
    serverList      []string
    lastRefreshTime int64
    cursor          int
}

// get nacos ip list from address by env
func (manager *ServerManager) RefreshServerListIfNeed() []string {
    if CurrentMillis()-manager.lastRefreshTime < 60*1000 && len(manager.serverList) > 0 {
        return manager.serverList
    }

    nacosServerList := os.Getenv("nacos_server_list")

    var list []string
    list = strings.Split(nacosServerList, ",")

    var servers []string
    for _, line := range list {
        if line != "" {
            servers = append(servers, strings.TrimSpace(line))
        }
    }

    if len(servers) > 0 {
        if !reflect.DeepEqual(manager.serverList, servers) {
            NacosClientLogger.Info("server list is updated, old: ", manager.serverList, ", new: ", servers)
        }
        manager.serverList = servers

        manager.lastRefreshTime = CurrentMillis()
    }

    return manager.serverList
}

func (manager *ServerManager) NextServer() string {
    manager.RefreshServerListIfNeed()

    if len(manager.serverList) == 0 {
        panic("no nacos server avialible.")
    }

    return manager.serverList[rand.Intn(len(manager.serverList))]
}

func (manager *ServerManager) SetServers(servers []string) {
    manager.serverList = servers
}

func (manager *ServerManager) GetServerList() []string {
    return manager.serverList
}

ServerManager定义了serverList、lastRefreshTime、cursor属性;它提供了RefreshServerListIfNeed、NextServer、SetServers、GetServerList方法;其中NextServer会先执行RefreshServerListIfNeed在返回随机的server;RefreshServerListIfNeed方法会根据lastRefreshTime来判断是否需要refresh,若要refresh则重新通过os.Getenv("nacos_server_list")获取server列表,然后更新lastRefreshTime

实例

nacos-coredns-plugin/nacos/server_manager_test.go

func TestServerManager_NextServer(t *testing.T) {
    os.Setenv("nacos_server_list", "2.2.2.2,3.3.3.3")
    sm := ServerManager{}
    sm.RefreshServerListIfNeed()
    ip := sm.NextServer()
    if strings.Compare(ip, "2.2.2.2") == 0 ||
        strings.Compare(ip, "3.3.3.3") == 0 {
        t.Log("ServerManager.NextServer test is passed.")
    }
}

func TestServerManager_RefreshServerListIfNeed(t *testing.T) {
    os.Setenv("nacos_server_list", "2.2.2.2,3.3.3.3")
    sm := ServerManager{}
    sm.RefreshServerListIfNeed()

    if len(sm.serverList) == 2 {
        t.Log("ServerManager.RefreshServerListIfNeed test is passed.")
    }

}

小结

nacos-coredns-plugin的ServerManager定义了serverList、lastRefreshTime、cursor属性;它提供了RefreshServerListIfNeed、NextServer、SetServers、GetServerList方法。

doc

上一篇下一篇

猜你喜欢

热点阅读