zookeeper-编程

使用cli操作zookeeper

//创建节点
create /test "hello"
create /test/dr1 null
create -s /test/index null //创建顺序节点
create -s -e /test/index null //创建顺序临时节点
//获取节点,设置监听
get /test/dr watch //对/test/dr进行监听,只监听一次
//设置数据
set /test/dr 111
//监听节点中子节点的变化
ls2 /test watch 
ls  /test //列出子节点
delete /test //删除单个节点,前提是节点中么有子节点
rmr /test //删除节点,及其下面的子节点

java操作zookeeper

  • 创建连接
public ZooKeeper connect(String host) throws IOException,InterruptedException {

        zoo = new ZooKeeper(host,5000,new Watcher() {
        //连接成功后回调
            public void process(WatchedEvent we) {
                if (we.getState() == Event.KeeperState.SyncConnected) {
                    connectedSignal.countDown();
                }
            }
        });

        connectedSignal.await();
        return zoo;
    }
  • 对zookeeper上的节点进行操作
//创建节点,在创建时需要指定节点的安全权限,节点类型(是否为临时节点、是否为顺序节点)。返回的为节点名称(可能和创建的节点名称不同,例如顺序节点)
String createStr=zooKeeper.create("/test/java1","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

//在节点上设置监听
zooKeeper.getData(PATH, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println(watchedEvent.getType());
                    try {
                        System.out.println(new String(finalZooKeeper.getData(PATH,false,null)));
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },null);

    //修改数据前需要先判断节点是否存在,同时获取到节点上的版本号(可以从stat中获取)
    Stat stat=zooKeeper.exists(PATH,false);
    System.out.println(stat.getVersion());
    zooKeeper.setData(PATH,"hello zk".getBytes(),stat.getVersion());

    //获取所有的子节点
    List<String> childrenList=zooKeeper.getChildren("/test",false);

    //删除节点,删除时也需要获取到版本号
    zooKeeper.delete("/test/dr",stat.getVersion());

猜你喜欢

转载自blog.csdn.net/designer01/article/details/82563441