Java Code Examples for org.I0Itec.zkclient.ZkClient#exists()

The following examples show how to use org.I0Itec.zkclient.ZkClient#exists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpServiceDiscovery.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    Boolean register = env.getProperty("soul.http.register", Boolean.class, false);
    if (!register) {
        return;
    }
    String zookeeperUrl = env.getProperty("soul.http.zookeeperUrl", "");
    if (StringUtils.isNoneBlank(zookeeperUrl)) {
        zkClient = new ZkClient(zookeeperUrl, 5000, 2000);
        boolean exists = zkClient.exists(ROOT);
        if (!exists) {
            zkClient.createPersistent(ROOT, true);
        }
        contextPathList = zkClient.getChildren(ROOT);
        updateServerNode(contextPathList);
        zkClient.subscribeChildChanges(ROOT, (parentPath, childs) -> {
            final List<String> addSubscribePath = addSubscribePath(contextPathList, childs);
            updateServerNode(addSubscribePath);
            contextPathList = childs;
        });
    }
}
 
Example 2
Source File: ServerManagerMonitor.java    From javabase with Apache License 2.0 6 votes vote down vote up
private static void monitor() {
    ZkClient zc=new ZkClient("localhost:2181",1000);
    //创建监控节点
    if(!zc.exists("/monitor"))
    zc.create("/monitor",null, CreateMode.PERSISTENT);

    if(!zc.exists("/monitor/client"))
    zc.create("/monitor/client",null, CreateMode.PERSISTENT);

    zc.subscribeChildChanges("/monitor/client",new IZkChildListener(){
        @Override
        public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
            System.out.println("------------客户端发生变化---------childPath="+parentPath );
            currentChilds.forEach((String childPath)->{
                System.out.println("parentPath = [" + parentPath + "], currentChilds = [" + currentChilds + "]");
            });
        }
    });



}
 
Example 3
Source File: ZkClientHelper.java    From sumk with Apache License 2.0 6 votes vote down vote up
public static void makeSure(ZkClient client, final String dataPath) {
	int start = 0, index;
	while (true) {
		index = dataPath.indexOf("/", start + 1);

		if (index == start + 1) {
			return;
		}
		String path = dataPath;
		if (index > 0) {
			path = dataPath.substring(0, index);
			start = index;
		}
		if (!client.exists(path)) {
			try {
				client.createPersistent(path);
			} catch (Exception e) {
				Logs.system().warn(path + " create failed.", e);
			}
		}

		if (index < 0 || index == dataPath.length() - 1) {
			return;
		}
	}
}
 
Example 4
Source File: IncrementIdGen.java    From SkyEye with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 利用zookeeper
 * @return
 */
@Override
public String nextId() {
    String app = this.registerDto.getApp();
    String host = this.registerDto.getHost();
    ZkClient zkClient = this.registerDto.getZkClient();
    String path = Constants.ZK_REGISTRY_ID_ROOT_PATH + Constants.SLASH + app + Constants.SLASH + host;
    if (zkClient.exists(path)) {
        // 如果已经有该节点,表示已经为当前的host上部署的该app分配的编号(应对某个服务重启之后编号不变的问题),直接获取该id,而无需生成
        return zkClient.readData(Constants.ZK_REGISTRY_ID_ROOT_PATH + Constants.SLASH + app + Constants.SLASH + host);
    } else {
        // 节点不存在,那么需要生成id,利用zk节点的版本号每写一次就自增的机制来实现
        Stat stat = zkClient.writeDataReturnStat(Constants.ZK_REGISTRY_SEQ, new byte[0], -1);
        // 生成id
        String id = String.valueOf(stat.getVersion());
        // 将数据写入节点
        zkClient.createPersistent(path, true);
        zkClient.writeData(path, id);
        return id;
    }
}
 
Example 5
Source File: ZkCoordinationUtilsFactory.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * if ZkConnectString contains namespace path at the end, but it does not exist we should fail
 * @param zkConnect - connect string
 * @param zkClient - zkClient object to talk to the ZK
 */
public static void validateZkNameSpace(String zkConnect, ZkClient zkClient) {
  ConnectStringParser parser = new ConnectStringParser(zkConnect);

  String path = parser.getChrootPath();
  if (Strings.isNullOrEmpty(path)) {
    return; // no namespace path
  }

  LOG.info("connectString = " + zkConnect + "; path =" + path);

  // if namespace specified (path above) but "/" does not exists, we will fail
  if (!zkClient.exists("/")) {
    throw new SamzaException("Zookeeper namespace: " + path + " does not exist for zk at " + zkConnect);
  }
}
 
Example 6
Source File: ConfigStateHolder.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
private static void syncConfigIfMiss(String profile,ZkClient zkClient){

	if(!zkClient.exists(ZK_ROOT_PATH)){
		zkClient.createPersistent(ZK_ROOT_PATH, true);
		return;
	}
	
	String parentPath = ZK_ROOT_PATH + "/" + profile;
	if(!zkClient.exists(parentPath)){
		zkClient.createPersistent(parentPath, true);
		return;
	}
	List<String> apps = zkClient.getChildren(parentPath);
	for (String app : apps) {
		parentPath = ZK_ROOT_PATH + "/" + profile + "/" + app + "/nodes";
		
		int activeNodeCount = zkClient.countChildren(parentPath);
		if(activeNodeCount == 0)continue;
		List<ConfigState> localCacheConfigs = configStates.get(app + "#" + profile);
		
		if(activeNodeCount > 0 && (localCacheConfigs == null || localCacheConfigs.size() < activeNodeCount)){
			zkClient.writeData(parentPath, NOTIFY_UPLOAD_CMD);
			logger.info("send cmd[{}] on path[{}]",NOTIFY_UPLOAD_CMD,parentPath);
		}
	}
}
 
Example 7
Source File: SendCounterHandler.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public SendCounterHandler(String producerGroup, ZkClient zkClient) {
	this.zkClient = zkClient;
	this.producerGroup =producerGroup;
	//
	groupPath = ROOT + "/" + producerGroup;
	if(!zkClient.exists(groupPath)){
		zkClient.createPersistent(groupPath, true);
	}
	initCollectionTimer();
}
 
Example 8
Source File: ZkRegister.java    From netty-pubsub with MIT License 5 votes vote down vote up
/**
 * zookeeper�ڵ�ע��
 * @param path  �ӽڵ����·��
 * @param data  �ӽڵ�ip:port
 */
public void register(String path,Object data){
	  zkc=new ZkClient(new ZkConnection(CONNECT_ADDR_SINGLE),SESSION_OUTTIME);
	  if(!zkc.exists(ROOT_PATH)){
        	zkc.createPersistent(ROOT_PATH,"brokerList");
        	LOGGER.info("��zk�ڵ��ʼ���ɹ���");
        };
        //������ʱ�ڵ�
        String createEphemeralSequential = zkc.createEphemeralSequential(path, data);
        //���õ�ǰzk·��
        this.currentZKPath=createEphemeralSequential;
        LOGGER.info("��brokerע�᡿path->"+createEphemeralSequential+" data->"+data+" status=SUCCESS");
}
 
Example 9
Source File: MonitorCluster.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public boolean checkPath(ZkClient zkClient, String path){
	boolean isExists = zkClient.exists(path);
	if(!isExists){
		logger.error("invalid zk path:{}", path);
		return false;
	}
	
	return true;
}
 
Example 10
Source File: SafeZclient.java    From javabase with Apache License 2.0 5 votes vote down vote up
private static void ls() {
	for (int i = 0; i <20 ; i++) {
		ZkClient zc = new ZkClient("127.0.0.1:2181");
		if(!zc.exists("/tt"))
		zc.create("/tt", "test", CreateMode.EPHEMERAL);
		log.info(zc.readData("/tt"));
	}
}
 
Example 11
Source File: ZKConfigHandler.java    From sumk with Apache License 2.0 5 votes vote down vote up
public static NamePairs readAndListen(String zkUrl, String path, IZkDataListener listener) {
	ZkClient client = ZkClientHelper.getZkClient(zkUrl);
	if (!client.exists(path)) {
		return null;
	}
	String data = ZkClientHelper.data2String(client.readData(path));
	if (listener != null) {
		client.subscribeDataChanges(path, listener);
	}
	return new NamePairs(data);
}
 
Example 12
Source File: NodeDAO.java    From shepher with Apache License 2.0 5 votes vote down vote up
public boolean exists(String cluster, String path) {
    ZkClient zkClient = ZkPool.getZkClient(cluster);
    try {
        if (zkClient == null) {
            return false;
        }
        return zkClient.exists(path);
    } finally {
        ZkPool.releaseZkClient(cluster, zkClient);
    }
}
 
Example 13
Source File: MonitorCluster.java    From jlogstash-input-plugin with Apache License 2.0 5 votes vote down vote up
public boolean checkPath(ZkClient zkClient, String path){
	boolean isExists = zkClient.exists(path);
	if(!isExists){
		logger.error("invalid zk path:{}", path);
		return false;
	}
	
	return true;
}
 
Example 14
Source File: ZkUtil.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 获取数据
 * @param zk
 * @param path
 * @return
 */
public static <T extends Object> T getData(ZkClient zk,String path){
	T t=null;
	if(zk.exists(path)){
	   t=zk.readData(path);
	}
	return t;
}
 
Example 15
Source File: ZkUtil.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 更新参数,没有就新增
 * @param zk
 * @param path
 * @param data
 * @return
 */
public static boolean setData(ZkClient zk,String path,String data){
	boolean falg=false;
	if(zk.exists(path)){
	   zk.writeData(path, data);
	   falg=true;
	}
	return falg;
}
 
Example 16
Source File: ZkRegisterCenter.java    From krpc with MIT License 5 votes vote down vote up
public static void register() {
    try {

        ZookeeperInfo zookeeperInfo = Global.getInstance().getZookeeperInfo();
        zc = new ZkClient(zookeeperInfo.getAddr(), zookeeperInfo.getSessionTimeOut(), zookeeperInfo.getConnectionTimeOut());

        StringBuffer stringBuffer = new StringBuffer("/krpc");

        if (!zc.exists(stringBuffer.toString())) {
            zc.create(stringBuffer.toString(), "", CreateMode.PERSISTENT);

            log.info("创建根节点krpc");
        }
        stringBuffer.append("/").append(Global.getInstance().getServiceName());

        if (!zc.exists(stringBuffer.toString())) {
            zc.create(stringBuffer.toString(), "", CreateMode.PERSISTENT);
            log.info("创建{}服务节点", Global.getInstance().getServiceName());
        }

        stringBuffer.append("/").append(Global.getInstance().getIp()).append(":").append(Global.getInstance().getPort());

        zc.create(stringBuffer.toString(), Global.getInstance().getServiceName(), CreateMode.EPHEMERAL);
    } catch (Exception e) {
        log.error("register error!", e);
    }
}
 
Example 17
Source File: LocalCacheUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Notify resource changed.
 * 向zookeeper注册中心广播 notifyName 对应的资源改变
 * 
 * @param notifyName the resource name
 */
public static void notifyResourceChanged(String notifyName) {
    ZkClient zClient = getZkClient();
    Long nanoTime = System.nanoTime();
    String resourcePath = getResourcePath(notifyName);
    if (!zClient.exists(resourcePath)) {
        zClient.createPersistent(resourcePath, true);
    }
    zClient.writeData(resourcePath, nanoTime);
}
 
Example 18
Source File: LocalCacheUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Long getResourceNano(String notifyName) {
    String resourcePath = getResourcePath(notifyName);
    ZkClient zClient = getZkClient();
    if (zClient.exists(resourcePath)) {
        Stat stat = new Stat();
        Long nanoTime = zClient.readData(resourcePath, stat);
        return nanoTime;
    }
    return null;
}
 
Example 19
Source File: ZkUtil.java    From java-study with Apache License 2.0 2 votes vote down vote up
/**
 * 创建目录不添加参数
 * 也可以创建层级目录,格式: /test/test1/test1-1
 * @param zk
 * @param path
 * @return
 */
public static void create(ZkClient zk,String path) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException{
	if(!zk.exists(path)){
		zk.createPersistent(path,true);
	}
}
 
Example 20
Source File: ZkUtil.java    From java-study with Apache License 2.0 2 votes vote down vote up
/**
 * 创建目录并添加参数
 * @param zk
 * @param path
 * @param data
 * @return
 */
public static void create(ZkClient zk,String path,String data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException{
	if(!zk.exists(path)){
		zk.create(path,data,CreateMode.PERSISTENT);
	}
}