//服务地址列表
private volatile List<String> serverAddressList=new ArrayList<String>();
/**
* 初始化服务地址信息
* @param serviceName 服务名称
* @param zkServiceStr zk地址
* @param rootPath 根路径
*/
public void init(String serviceName,String zkServiceStr,String rootPath){
String servicePath=rootPath+"/"+serviceName;
ZkClient zkClient=new ZkClient(zkServiceStr);
boolean serviceExists=zkClient.exists(servicePath);
if(serviceExists){
//如果服务节点存在,那么取出下面所有的服务地址的临时节点
serverAddressList=zkClient.getChildren(servicePath);
}else{
throw new RuntimeException("service not exits!");
}
//注册事件监听
zkClient.subscribeChildChanges(servicePath, new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
serverAddressList=currentChilds;
}
});
}
欢迎加入-微信群聊【聊技术、聊生活】