node 操作demo
package com.qzq.zookeeperdemo;
import java.io.IOException;
import java.util.ArrayList;
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.ACL;
import org.junit.Before;
import org.junit.Test;
public class ZookeeperClientDemo {
ZooKeeper zk = null;
@Before
public void setUp() throws Exception{
zk = new ZooKeeper("mini1:2181,mini2:2181,mini3:2181",1000,null);
}
@Test
public void testCreate() throws Exception{
String create = zk.create("/zhiquanqiao", "hanyuli".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(create);
}
@Test
public void testUpdate() throws Exception{
zk.setData("/zhiquanqiao", "my girl:hanyu li".getBytes(), -1);
zk.close();
}
@Test
public void testGet() throws Exception{
byte[] data = zk.getData("/zhiquanqiao", false, null);
System.out.println(new String(data,"UTF-8"));
zk.close();
}
@Test
public void testListChildren() throws Exception{
List<String> children = zk.getChildren("/data", false);
for(String child:children){
System.out.println(child);
}
zk.close();
}
@Test
public void testRm() throws Exception{
zk.delete("/zhiquanqiao", 1);
zk.close();
}
}
Watch 相关demo
package com.qzq.zookeeperdemo;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;
public class ZookeeperWatchDemo {
ZooKeeper zk = null;
@Before
public void init() throws Exception{
zk = new ZooKeeper("mini1:2181,mini2:2181,mini3:2181",2000,new Watcher(){
public void process(WatchedEvent event) {
if(event.getState() == KeeperState.SyncConnected && event.getType() == EventType.NodeDataChanged){
System.out.println(event.getPath());
System.out.println(event.getType());
System.out.println("test event ");
try{
System.out.println(new String(zk.getData(event.getPath(), true, null),"UTF-8"));
}catch(Exception e){
e.printStackTrace();
}
}else if(event.getState() == KeeperState.SyncConnected && event.getType() == EventType.NodeChildrenChanged){
System.out.println("子节点变化了");
}
}
});
}
@Test
public void testGetWatch() throws Exception{
while(true){
byte[] data = zk.getData("/data", true, null);
System.out.println(new String (data,"UTF-8"));
Thread.sleep(30000);
}
}
}