import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class ConnectionWatcher implements Watcher {
private CountDownLatch connectedSignal = new CountDownLatch(1);
private static final int SESSION_TIMEOUT = 5000;
ZooKeeper zk;
public void connect(String hosts) throws InterruptedException, IOException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
@Override
public void process(WatchedEvent event) {
if(event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void close() throws InterruptedException {
zk.close();
}
}
创建新建节点和获取节点值类
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
/**
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class HelloZookeeper extends ConnectionWatcher{
public void createNode(String nodeName, String nodeValue)
throws KeeperException, InterruptedException {
String path = "/" + nodeName;
String createPath = zk.create(path, nodeValue.getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("Created znode:"+createPath);
}
public void getValue(String nodeName) throws KeeperException, InterruptedException {
String path = "/" + nodeName;
byte[] value = zk.getData(path, false, null);
System.out.printf("[%s,%s]", path, new String(value));
}
public static void main(String[] args) throws Exception, IOException {
// 1 - Connect
JoinGroup joinGroup = new JoinGroup();
joinGroup.connect("192.168.80.219");
// 2 - Created node
joinGroup.createNode("hello", "world");
// 3- Get value
joinGroup.getValue("hello");
TimeUnit.HOURS.sleep(1);
}
} 执行显示如下
Created znode:/hello
[/hello,world]
另外官网的zookeeper示例代码也很赞,已经附在文后。
version1.0 first created 2014-05-20
version2.0 删除无用shell显示,精简排版 2014-06-04
转载请标明作者和原文链接
ifuteng#gmail.com 2014/5/20