用Junit测试每个方法
1) 创建连接
ZooKeeper zk = new ZooKeeper("chun1:2181,chun2:2181," +"chun3:2181,chun4:2181,chun5:2181",3000,null);
2) 创建节点
@Test
public void testCreate() throws KeeperException, InterruptedException {
//参数1.节点路径名字 参数2:数据 参数3:访问权限 参数4:节点类型String create = zk.create("/demo123", "hello zookeeper".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println(create);zk.close();
}
3)修改
//修改
@Test
public void testUpdata() throws KeeperException, InterruptedException {// 参数1:节点路径 参数2:修改的数据 参数3:版本zk.setData("/demo123", "do't hello zookeeper".getBytes(),-1);zk.close();}
4)查询
@Test
public void testGetdata() throws KeeperException, InterruptedException {//参数1:路径 参数2:是否要监听: 参数3:所要获取的数据的版本(null表示最新版本)byte[] data = zk.getData("/demo123", false, null); String s = new String(data);System.out.println(s);zk.close();
}
5)查询子节点
@Test
public void testChilddrend() throws KeeperException, InterruptedException {
//参数1:节点路径 参数2:是否需要监听List<String> children = zk.getChildren("/hbase", false);System.out.println(children);zk.close();
}
6)删除
@Test
public void testRm() throws KeeperException, InterruptedException {//参数1:节点路径 参数2:所要删除的数据的版本,-1(表示所有版本)zk.delete("/demo123",-1);zk.close();
}
下面是整个代码
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;import java.io.IOException;
import java.util.List;public class ZookeeperDemo {ZooKeeper zk = new ZooKeeper("chun1:2181,chun2:2181," +"chun3:2181,chun4:2181,chun5:2181",3000,null);public ZookeeperDemo() throws IOException {}//创建@Testpublic void testCreate() throws KeeperException, InterruptedException {//参数1.节点路径名字 参数2:数据 参数3:访问权限 参数4:节点类型String create = zk.create("/demo123", "hello zookeeper".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println(create);zk.close();}//修改@Testpublic void testUpdata() throws KeeperException, InterruptedException {// 参数1:节点路径 参数2:修改的数据 参数3:版本zk.setData("/demo123", "do't hello zookeeper".getBytes(),-1);zk.close();}//查询@Testpublic void testGetdata() throws KeeperException, InterruptedException {//参数1:路径 参数2:是否要监听: 参数3:所要获取的数据的版本(null表示最新版本)byte[] data = zk.getData("/demo123", false, null);String s = new String(data);System.out.println(s);zk.close();}//查询子节点@Testpublic void testChilddrend() throws KeeperException, InterruptedException {//参数1:节点路径 参数2:是否需要监听List<String> children = zk.getChildren("/hbase", false);System.out.println(children);zk.close();}//删除@Testpublic void testRm() throws KeeperException, InterruptedException {//参数1:节点路径 参数2:所要删除的数据的版本,-1(表示所有版本)zk.delete("/demo123",-1);zk.close();}
}