小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
接着调用checkUpdateDataIds方法,基于长连接方式来监听服务端配置变化,根据变化数据的key去服务端获取最新数据,checkUpdateDataIds调用checkUpdateConfigStr方法。
List<String> checkUpdateConfigStr(String probeUpdateString,boolean inInitializingCacheList) throws IOException{
List<String> params = Arrays.asList(Constants.PROBE_MODIFY_REQUEST,probeUpdateString);
List<String> headers=new ArrayList<String>(2);
headers.add("Long-Pulling-Timeout");
headers.add(“”+timeout);
if(isInitializingCacheLIst){
headers.add("Long-Pulling-Timeout-No-Hangup");
headers.add("true");
}
if(StringUtils.isBlank(probeUpdateString)){
return Collections.emptyList();
}
try{
HttpResult result=agent.httpPost(Constants.CONFIG_CONTROLLER_PATH+"/listener",headers,params,agent.getEncode(),timeout);
if(HttpURLConnection.HTTP_OK == result.code){
setHealthServer(true);
return parseUpdateDataIdResponse(result.content);
}else{
setHealthServer(false);
LOGGER.error("[{}][check-update] get changed dataId error,code:{}",agent.getName(),result.code);
}
}catch(IOException e){
setHealthServer(false);
LOGGER.error("[]"+agent.getName()+"][check-update] get changed dataId exception",e);
throw e;
}
return Collections.emptyList();
}
checkUpdateConfigStr方法通过agent.httpPost调用/listener接口实现长轮询请求,长轮询请求在实现层只是设置一个比较长的超时时间,默认是30s。如果服务端的数据发生修改,客户端会收到一个HttpResult,服务端返回的是存在数据变更的dataId、group、tenant,获取信息后,在LongPollingRunnable的run方法调用getServerConfig去Nacos服务器上读取具体的配置内容。
public String getServerConfig(String dataId,String group,String tenant,long readTimeout) throw NacosException{
HttpResult result=null;
try{
List<String> params = null;
if(StringUtls.isBlank(tenant)){
params=Arrays.asList("dataId",dataId,"group",group);
}else{
params=Arrays.asList("dataId",dataI,"group",group,"tenant",tenant);
}
result=agent.httpGet(Constants.CONFIG_CONTROLLER_PATH,null,params,agent.getEncode,readTimeout);
}
}
服务端长轮询处理机制
从Nacos源码中找到nacos-config模块,在controller包中提供了一个ConfigController类来实现配置的基本操作,有一个/listener接口,它是客户端发起数据监听接口。
- 获取客户端需要监听发生变化的配置,并计算MD5值。
- inner.doPollingConfig开始执行长轮询请求