标签:
用java操作zookeeper
package cn.sniper.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.TreeSet;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
public class ZookeeperUtil {
@Test
public void helloword() {
//端口默认是2181
//String connectString = "192.168.1.231";
String connectString = "192.168.1.231:2181";
int sessionTimeout = 20000;
try {
ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
System.out.println(event);
}
});
System.out.println(zk);
zk.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void create() {
String connectString = "192.168.1.231:2181";
int sessionTimeout = 20000;
try {
ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
System.err.println("事件类型:" + event.getType());
}
});
//创建节点
zk.create("/sniper1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
@Test
public void fifoIn() {
String connectString = "192.168.1.231,192.168.1.232,192.168.1.233";
int sessionTimeout = 20000;
try {
ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
System.err.println("事件类型:" + event.getType());
}
});
//每个客户端连进来的时候,都在fifo下创建一个有序节点 模拟10个客户端连接进入
for(int i=0; i<10; i++) {
zk.create("/fifo/", String.valueOf(System.currentTimeMillis()).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
zk.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
@Test
public void fifoOut() {
String connectString = "192.168.1.231,192.168.1.232,192.168.1.233";
int sessionTimeout = 30000;
try {
ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
System.err.println("事件类型:" + event.getType());
}
});
List<String> children = zk.getChildren("/fifo", new Watcher() {
public void process(WatchedEvent event) {
System.err.println("事件类型:" + event.getType());
}
});
//由于节点的有序性,将节点用treeSet排序一下,取得第一个元素,就可以做到先进先出队列了
TreeSet<String> set = new TreeSet<String>(children);
String child = set.first();
System.err.println(child);
zk.delete("/fifo/"+child, -1);
zk.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
}
标签:
原文地址:http://my.oschina.net/sniperLi/blog/499165