1. 创建maven项目,导入zookeeper相关包
org.apache.zookeeper
zookeeper
3.4.6
junit
junit
4.13-beta-2
compile
2. 连接zookeeper
@Before
// 连接zookeeper
public void init() throws IOException {
Watcher watcher = new Watcher() {
//收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.getType()+","+watchedEvent.getPath());
}
};
//三个参数:ip,超时时间,监听器
zooKeeper = new ZooKeeper("192.168.231.132:2181", 5000, watcher);
}
3.完整代码
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class TestDemo {
private ZooKeeper zooKeeper;
@Before
// 连接zookeeper
public void init() throws IOException {
Watcher watcher = new Watcher() {
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.getType()+","+watchedEvent.getPath());
}
};
//三个参数:ip,超时时间,监听器
zooKeeper = new ZooKeeper("192.168.231.132:2181", 5000, watcher);
}
//获取子节点
@Test
public void getChild(){
/*
* 传入2个参数
* 1、指定获取哪个节点的孩子
* 2、是否使用监听器(watcher),true表示使用以上的监听功能
*/
try {
List children = zooKeeper.getChildren("/", true);
for(String str:children){
System.out.println(str);
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//创建节点
@Test
public void createNode(){
String s = null;
try {
/*
* 传入四个参数
* 1、创建的节点
* 2、节点数据
* 3、节点的权限,OPEN_ACL_UNSAFE表示内部应用权限
* 4、节点类型,4种:持久化节点,带序列持久化节点,临时节点,带序列的临时节点
*/
s = zooKeeper.create("/b", "bb".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(s);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//获取节点
@Test
public void getData(){
byte[] data = new byte[0];
try {
data = zooKeeper.getData("/b", false, null);
System.out.println(new String(data));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//删除节点
@Test
public void deleteNode(){
try {
zooKeeper.delete("/b",-1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
//修改节点
@Test
public void updateNode(){
try {
zooKeeper.setData("/a","hhhhhh".getBytes(),-1);
//查看是否修改成功
byte[] data = zooKeeper.getData("/a", false, null);
System.out.println(new String(data));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断节点是否存在
@Test
public void testExist(){
try {
Stat stat = zooKeeper.exists("/b", false);
System.out.println(stat==null?"不存在":"存在");
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}