序
本文主要研究一下 nacos client 的 ServerListManager 的 start
ServerListManager
nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java
public class ServerListManager {private static final Logger LOGGER = LogUtils.logger(ServerListManager.class);
private static final String HTTPS = "https://";
private static final String HTTP = "http://";
//......
public synchronized void start() throws NacosException {if (isStarted || isFixed) {return;}
GetServerListTask getServersTask = new GetServerListTask(addressServerUrl);
for (int i = 0; i < initServerlistRetryTimes && serverUrls.isEmpty(); ++i) {getServersTask.run();
try {this.wait((i + 1) * 100L);
} catch (Exception e) {LOGGER.warn("get serverlist fail,url: {}", addressServerUrl);
}
}
if (serverUrls.isEmpty()) {LOGGER.error("[init-serverlist] fail to get NACOS-server serverlist! env: {}, url: {}", name,
addressServerUrl);
throw new NacosException(NacosException.SERVER_ERROR,
"fail to get NACOS-server serverlist! env:" + name + ", not connnect url:" + addressServerUrl);
}
TimerService.scheduleWithFixedDelay(getServersTask, 0L, 30L, TimeUnit.SECONDS);
isStarted = true;
}
//......
}
- ServerListManager 的 start 方法在非 isStarted 且非 isFixed 的条件下会执行 GetServerListTask,失败重试次数为 initServerlistRetryTimes,如果 serverUrls 为空则抛出 NacosException;如果不为空则注册该 getServersTask 每隔 30 秒执行一次来刷新 server list
GetServerListTask
nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java
public class ServerListManager {
//......
class GetServerListTask implements Runnable {
final String url;
GetServerListTask(String url) {this.url = url;}
@Override
public void run() {
/**
* get serverlist from nameserver
*/
try {updateIfChanged(getApacheServerList(url, name));
} catch (Exception e) {LOGGER.error("[" + name + "][update-serverlist] failed to update serverlist from address server!",
e);
}
}
}
private void updateIfChanged(List<String> newList) {if (null == newList || newList.isEmpty()) {LOGGER.warn("[update-serverlist] current serverlist from address server is empty!!!");
return;
}
List<String> newServerAddrList = new ArrayList<String>();
for (String server : newList) {if (server.startsWith(HTTP) || server.startsWith(HTTPS)) {newServerAddrList.add(server);
} else {newServerAddrList.add(HTTP + server);
}
}
/**
* no change
*/
if (newServerAddrList.equals(serverUrls)) {return;}
serverUrls = new ArrayList<String>(newServerAddrList);
iterator = iterator();
currentServerAddr = iterator.next();
EventDispatcher.fireEvent(new ServerlistChangeEvent());
LOGGER.info("[{}] [update-serverlist] serverlist updated to {}", name, serverUrls);
}
private List<String> getApacheServerList(String url, String name) {
try {HttpResult httpResult = HttpSimpleClient.httpGet(url, null, null, null, 3000);
if (HttpURLConnection.HTTP_OK == httpResult.code) {if (DEFAULT_NAME.equals(name)) {EnvUtil.setSelfEnv(httpResult.headers);
}
List<String> lines = IOUtils.readLines(new StringReader(httpResult.content));
List<String> result = new ArrayList<String>(lines.size());
for (String serverAddr : lines) {if (org.apache.commons.lang3.StringUtils.isNotBlank(serverAddr)) {String[] ipPort = serverAddr.trim().split(":");
String ip = ipPort[0].trim();
if (ipPort.length == 1) {result.add(ip + ":" + ParamUtil.getDefaultServerPort());
} else {result.add(serverAddr);
}
}
}
return result;
} else {LOGGER.error("[check-serverlist] error. addressServerUrl: {}, code: {}", addressServerUrl,
httpResult.code);
return null;
}
} catch (IOException e) {LOGGER.error("[check-serverlist] exception. url:" + url, e);
return null;
}
}
//......
}
- GetServerListTask 实现了 Runnable 接口,其 run 方法会通过 getApacheServerList 请求 addressServerUrl 获取服务端地址列表,然后执行 updateIfChanged 方法;该方法会判断 server list 是否有变更,有变更则更新 serverUrls,然后发布 ServerlistChangeEvent
小结
ServerListManager 的 start 方法在非 isStarted 且非 isFixed 的条件下会执行 GetServerListTask,失败重试次数为 initServerlistRetryTimes,如果 serverUrls 为空则抛出 NacosException;如果不为空则注册该 getServersTask 每隔 30 秒执行一次来刷新 server list
doc
- ServerListManager