ZooKeeper的java客户端api基本功能代码

package cn.edu360.zk.demo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class ZookepperClientDemo {
	ZooKeeper zk = null;
	
	@Before
	public void init() throws Exception {
		
		zk = new ZooKeeper("hadoop1:2181,hadoop2:2181,hadoop3:2181", 2000, null);
		
	}
	
	
	@Test
	public void testCreate() throws Exceptaion {
		//构造一个连接zookeeper的客户端对象
		
		//参数1:要创建节点路径    参数2:数据      参数3:访问权限      参数4:节点类型
		String create = zk.create("/eclipse", "hello eclipse".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		
		System.out.println(create);
		
		zk.close();
		
	}
	
	@Test
	public void testUpdate() throws Exception, KeeperException, InterruptedException {
		
		//参数1:节点路径   参数2:数据  参数3:要修改的版本 ,-1代表任何版本
		Stat stat = zk.setData("/eclipse", "我爱你".getBytes("UTF-8"), -1);
		
		zk.close();
	}
	
	
	
	@Test
	public void testGet() throws Exception{
		
		//参数1:节点路径  参数2:是否要监听  参数3 :所要获取的版本,null表示最新的版本
		byte[] data = zk.getData("/eclipse", false, null);
		System.out.println(new String(data,"UTF-8"));
		zk.close();
	}
	
	
	@Test
	public void testListChildern() throws Exception{
		
		//参数1:节点路径  参数2:是否要监听 ; 
		//注意返回的结果只有节点的名字,没有全路径;
		List<String> children = zk.getChildren("/cc", false);
		
		for (String child : children) {
			System.out.println(child);
		}
		
		zk.close();
	}
	
	
	
	@Test
	public void testRm() throws Exception{
		
		//参数1:节点路径  参数2:版本
		zk.delete("/eclipse", -1);
		
		zk.close();
	}
	

}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐