本文主要研究一下nacos-coredns-plugin的ServerManagergit
nacos-coredns-plugin/nacos/server_manager.gogithub
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.goapp
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方法。code