发布时间:2023-12-03 08:00
//服务地址列表
private volatile List serverAddressList=new ArrayList();
/**
* 初始化服务地址信息
* @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 currentChilds) throws Exception {
serverAddressList=currentChilds;
}
});
}