1.添加包依赖
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
<type>pom</type>
</dependency>
2.连接zookeeper
@Before
public void conn() throws IOException {
ZooKeeper zk = new ZooKeeper("master:2181,node1:2181,node2:2181",30000,null);
}
3.在zk上创建节点
@Test
/**
* 在zk上创建节点 并保存数据
* ZooDefs.Ids.OPEN_ACL_UNSAFE 不做任何权限认证
* CreateMode.PERSISTENT 创建永久节点
* CreateMode.EPHEMERAL 创建临时节点,连接断开自动删除
*
*/
public void createZNode() throws KeeperException, InterruptedException {
zk.create("/test1",
"data1".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT
);
}
@Test
public void createTempZNode() throws KeeperException, InterruptedException {
zk.create("/test2",
"data1".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL
);
}
4.监听创建的节点是否有变化
@Test
/**
* 非阻塞监听 /test1是否有变化
*/
public void watchEvent(){
try {
zk.exists("/test1", new Watcher() {
public void process(WatchedEvent event) {
System.out.println(event);
System.out.println("/test1有变化");
}
});
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true){
}
}
5.关闭
@After
public void close() {
try {
zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
完整代码
public class ZKAPI {
ZooKeeper zk=null;
@Before
public void conn() throws IOException {
zk = new ZooKeeper("master:2181,node1:2181,node2:2181",30000,null);
}
@Test
/**
* 在zk上创建节点 并保存数据
* ZooDefs.Ids.OPEN_ACL_UNSAFE 不做任何权限认证
* CreateMode.PERSISTENT 创建永久节点
* CreateMode.EPHEMERAL 创建临时节点,连接断开自动删除
*
*/
public void createZNode() throws KeeperException, InterruptedException {
zk.create("/test1",
"data1".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT
);
}
@Test
public void createTempZNode() throws KeeperException, InterruptedException {
zk.create("/test2",
"data1".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL
);
}
@Test
/**
* 非阻塞监听 /test1是否有变化
*/
public void watchEvent(){
try {
zk.exists("/test1", new Watcher() {
public void process(WatchedEvent event) {
System.out.println(event);
System.out.println("/test1有变化");
}
});
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true){
}
}
@After
public void close() {
try {
zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|