序
本文次要钻研一下 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
- nacos-coredns-plugin