Zookeeper服务框架之Java API的使用(三)


一、开发环境配置

第一:打开Zookeeper服务端,参考之前的博客。

第二:配置开发环境环境可以有两种方式:

① 直接下载相关的依赖Jar包,然后在IDE中添加依赖。

② 建立maven项目,使用maven进行依赖管理。

 

现在开发步骤(① 手动添加依赖至IDE)如下:

步骤一:点击http://hadoop.apache.org/zookeeper/下载对应版本的Jar包,包括(jar、javadoc.jar、sources.jar),笔者对应下载的Zookeeper3.4.9版本。

步骤二:打开IDE(笔者使用eclispe),新建名为zookeeperApp1的java项目,并添加相应的jar包。

Zookeeper服务框架之Java API的使用(三)_第1张图片

步骤三:新建包、Java类进行测试。

 

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperApp1Test {
    
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        
        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher(){

            @Override
            public void process(WatchedEvent event) {
                System.out.println("Receive watched event : " + event);
                if (KeeperState.SyncConnected == event.getState()) {
                    connectedSemaphore.countDown();
                }
            }}
        );
        
        System.out.println(zookeeper.getState());
        
        try {
            connectedSemaphore.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Zookeeper session established");
        
    }
}


运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第2张图片

 

现在开发步骤(② 使用maven管理依赖)如下:

步骤一:新建maven项目.

Zookeeper服务框架之Java API的使用(三)_第3张图片

步骤二:配置pom.xml文件如下:


  4.0.0

  com.npf
  zookeeperApp2
  0.0.1-SNAPSHOT
  jar

  zookeeperApp2
  http://maven.apache.org

  
    UTF-8
  

  
        
            junit
            junit
            3.8.1
            test
        

        
            org.apache.zookeeper
            zookeeper
            3.4.9
        

        
            log4j
            log4j
            1.2.16
        

        
            org.slf4j
            slf4j-api
            1.6.1
        

    
    
    
      
        jdk-1.7
        
            true
            1.7
        
        
            1.7
            1.7
            1.7
        
     
  
    

步骤三:新建java类进行测试:

 

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperApp2Test {
    
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        
        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher(){

            @Override
            public void process(WatchedEvent event) {
                System.out.println("Receive watched event : " + event);
                if (KeeperState.SyncConnected == event.getState()) {
                    connectedSemaphore.countDown();
                }
            }}
        );
        
        System.out.println(zookeeper.getState());
        
        try {
            connectedSemaphore.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("Zookeeper session established");
        
    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第4张图片

二、操作示例

3.1  创建节点

创建节点有异步和同步两种方式。无论是异步或者同步,Zookeeper都不支持递归调用,即无法在父节点不存在的情况下创建一个子节点,如在/zk-ephemeral节点不存在的情况下创建/zk-ephemeral/ch1节点;并且如果一个节点已经存在,那么创建同名节点时,会抛出NodeExistsException异常。

① 同步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperCreateNodeAPITest {
    
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        
        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher(){

            @Override
            public void process(WatchedEvent event) {
                 if (KeeperState.SyncConnected == event.getState()) {
                    connectedSemaphore.countDown();
                 }
            }}
        );
        
        System.out.println(zookeeper.getState());
        connectedSemaphore.await();
        
        String path1 = zookeeper.create("/zk-test-ephemeral-", "datatest".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);    
        System.out.println("Success create znode: " + path1);
        
        String path2 = zookeeper.create("/zk-test-ephemeral-", "datatest".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);    
        System.out.println("Success create znode: " + path2);
        
    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第5张图片

结果表明已经成功创建了临时节点和临时顺序节点,在创建顺序节点时,系统会在后面自动增加一串数字。

② 异步方式

使用异步方式与同步方式的区别在于节点的创建过程(包括网络通信和服务端的节点创建过程)是异步的,在同步接口调用过程中,开发者需要关注接口抛出异常的可能,但是在异步接口中,接口本身不会抛出异常,所有异常都会在回调函数中通过Result Code来体现

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperCreateNodeAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {

        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000,
                new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (KeeperState.SyncConnected == event.getState()) {
                            connectedSemaphore.countDown();
                        }
                    }
                });

        System.out.println(zookeeper.getState());
        connectedSemaphore.await();

        zookeeper.create("/zk-test-ephemeral-", "datatest".getBytes(),
                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new IStringCallback(), "I am context. ");

        zookeeper.create("/zk-test-ephemeral-", "datatest".getBytes(),
                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,
                new IStringCallback(), "I am context. ");

        zookeeper.create("/zk-test-ephemeral-", "datatest".getBytes(),
                Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,
                new IStringCallback(), "I am context. ");
        
        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IStringCallback implements AsyncCallback.StringCallback {
    public void processResult(int rc, String path, Object ctx, String name) {
        System.out.println("Create path result: [" + rc + ", " + path + ", "
                + ctx + ", real path name: " + name);
    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第6张图片

结果表明已经成功使用异步方式创建了相应节点。

3.2 删除节点 

只允许删除叶子节点,即一个节点如果有子节点,那么该节点将无法直接删除,必须先删掉其所有子节点。同样也有同步和异步两种方式。 

① 同步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperDeleteNodeAPITest {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000,
                new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (KeeperState.SyncConnected == event.getState()) {
                            if (EventType.None == event.getType()
                                    && null == event.getPath()) {
                                connectedSemaphore.countDown();
                            }
                        }
                    }
                });

        connectedSemaphore.await();

        zookeeper.create(path, "testdata".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path);
        zookeeper.create(path + "/c1", "testdata".getBytes(),
                Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path + "/c1");

        try {
            zookeeper.delete(path, -1);
        } catch (Exception e) {
            System.out.println("fail to delete znode: " + path);
        }

        zookeeper.delete(path + "/c1", -1);
        System.out.println("success delete znode: " + path + "/c1");
        zookeeper.delete(path, -1);
        System.out.println("success delete znode: " + path);

        Thread.sleep(Integer.MAX_VALUE);
    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第7张图片

结果表明若节点有子节点,则无法将其删除,必须先删除其所有子节点。

② 异步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperDeleteNodeAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        ZooKeeper zookeeper = new ZooKeeper("npfdev1:2181", 5000,
                new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (KeeperState.SyncConnected == event.getState()) {
                            if (EventType.None == event.getType()
                                    && null == event.getPath()) {
                                connectedSemaphore.countDown();
                            }
                        }
                    }
                });

        connectedSemaphore.await();

        zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path);
        zookeeper.create(path + "/c1", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path + "/c1");

        zookeeper.delete(path, -1, new IVoidCallback(), null);
        zookeeper.delete(path + "/c1", -1, new IVoidCallback(), null);
        zookeeper.delete(path, -1, new IVoidCallback(), null);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IVoidCallback implements AsyncCallback.VoidCallback {

    @Override
    public void processResult(int rc, String path, Object ctx) {
        System.out.println(rc + ", " + path + ", " + ctx);
    }
}
运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第8张图片

结果结果表明第一次删除/zk-book的时异常,ResultCode为-111。

3.3 子节点获取

读取节点的子节点列表,同样可以使用同步和异步的方式进行操作。

① 同步方式  

package com.npf.test;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperGetNodeAPITest {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-1";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    } else if (event.getType() == EventType.NodeChildrenChanged) {
                        try {
                            System.out.println("ReGet Child:"
                                    + zookeeper.getChildren(event.getPath(),
                                            true));
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });

        connectedSemaphore.await();

        zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path);
        zookeeper.create(path + "/c1", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path + "/c1");
        List childrenList = zookeeper.getChildren(path, true);
        System.out.println(childrenList);

        zookeeper.create(path + "/c2", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path + "/c2");
        Thread.sleep(1000);
        zookeeper.create(path + "/c3", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path + "/c3");
        Thread.sleep(Integer.MAX_VALUE);

    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第9张图片

值得注意的是,Watcher通知是一次性的,即一旦触发一次通知后,该Watcher就失效了,因此客户端需要反复注册Watcher,即程序中在process里面又注册了Watcher,否则,将无法获取c3节点的创建而导致子节点变化的事件。

② 异步方式

package com.npf.test;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperGetNodeAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-2";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    } else if (event.getType() == EventType.NodeChildrenChanged) {
                        try {
                            System.out.println("ReGet Child:"
                                    + zookeeper.getChildren(event.getPath(),
                                            true));
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });

        connectedSemaphore.await();
        zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path);
        zookeeper.create(path + "/c1", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path + "/c1");

        zookeeper.getChildren(path, true, new IChildren2Callback(), null);

        zookeeper.create(path + "/c2", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path + "/c2");

        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IChildren2Callback implements AsyncCallback.Children2Callback {

    @Override
    public void processResult(int rc, String path, Object ctx,
            List children, Stat stat) {
        System.out.println("Get Children znode result: [response code: " + rc
                + ", param path: " + path + ", ctx: " + ctx
                + ", children list: " + children + ", stat: " + stat);

    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第10张图片

结果表示通过异步的方式可以获取子节点信息。

3.4 数据节点获取

对于节点的数据获取,同样存在同步和异步两种方式。

① 同步方式

 

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperGetDataAPITest {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-4";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    } else if (event.getType() == EventType.NodeDataChanged) {
                        try {
                            System.out.println("the data of znode "
                                    + event.getPath()
                                    + " is : "
                                    + new String(zookeeper.getData(
                                            event.getPath(), true, stat)));
                            System.out.println("czxID: " + stat.getCzxid()
                                    + ", mzxID: " + stat.getMzxid()
                                    + ", version: " + stat.getVersion());
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });

        connectedSemaphore.await();
        zookeeper.create(path, "123".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path);

        System.out.println("the data of znode " + path + " is : "
                + new String(zookeeper.getData(path, true, stat)));
        System.out.println("czxID: " + stat.getCzxid() + ", mzxID: "
                + stat.getMzxid() + ", version: " + stat.getVersion());

        zookeeper.setData(path, "1234".getBytes(), -1);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第11张图片

结果表明可以使用getData函数获取节点的数据。

② 异步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperGetDataAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-5";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    } else if (event.getType() == EventType.NodeDataChanged) {
                        try {
                            zookeeper.getData(event.getPath(), true,
                                    new IDataCallback(), null);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });

        connectedSemaphore.await();
        zookeeper.create(path, "123".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path);
        
        zookeeper.getData(path, true, new IDataCallback(), null);

        zookeeper.setData(path, "1234".getBytes(), -1);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IDataCallback implements AsyncCallback.DataCallback {
    public void processResult(int rc, String path, Object ctx, byte[] data,
            Stat stat) {
        System.out.println("rc: " + rc + ", path: " + path + ", data: "
                + new String(data));
        System.out.println("czxID: " + stat.getCzxid() + ", mzxID: "
                + stat.getMzxid() + ", version: " + stat.getVersion());
    }
}

Zookeeper服务框架之Java API的使用(三)_第12张图片

结果表明采用异步方式同样可方便获取节点的数据。

3.5 更新数据

在更新数据时,setData方法存在一个version参数,其用于指定节点的数据版本,表明本次更新操作是针对指定的数据版本进行的,但是,在getData方法中,并没有提供根据指定数据版本来获取数据的接口,那么,这里为何要指定数据更新版本呢,这里方便理解,可以等效于CAS(compare and swap),对于值V,每次更新之前都会比较其值是否是预期值A,只有符合预期,才会将V原子化地更新到新值B。Zookeeper的setData接口中的version参数可以对应预期值,表明是针对哪个数据版本进行更新,假如一个客户端试图进行更新操作,它会携带上次获取到的version值进行更新,而如果这段时间内,Zookeeper服务器上该节点的数据已经被其他客户端更新,那么其数据版本也会相应更新,而客户端携带的version将无法匹配,无法更新成功,因此可以有效地避免分布式更新的并发问题

① 同步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperSetDataAPITest {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-6";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    }
                }
            }
        });

        connectedSemaphore.await();

        zookeeper.create(path, "123".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path);
        zookeeper.getData(path, true, null);

        Stat stat = zookeeper.setData(path, "456".getBytes(), -1);
        System.out.println("czxID: " + stat.getCzxid() + ", mzxID: "
                + stat.getMzxid() + ", version: " + stat.getVersion());
        Stat stat2 = zookeeper.setData(path, "456".getBytes(),
                stat.getVersion());
        System.out.println("czxID: " + stat2.getCzxid() + ", mzxID: "
                + stat2.getMzxid() + ", version: " + stat2.getVersion());
        try {
            zookeeper.setData(path, "456".getBytes(), stat.getVersion());
        } catch (KeeperException e) {
            System.out.println("Error: " + e.code() + "," + e.getMessage());
        }
        Thread.sleep(Integer.MAX_VALUE);

    }
}

Zookeeper服务框架之Java API的使用(三)_第13张图片

结果表明由于携带的数据版本不正确,而无法成功更新节点。其中,setData中的version参数设置-1含义为客户端需要基于数据的最新版本进行更新操作。

② 异步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperSetDataAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    public static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book-7";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                if (KeeperState.SyncConnected == event.getState()) {
                    if (EventType.None == event.getType()
                            && null == event.getPath()) {
                        connectedSemaphore.countDown();
                    }
                }
            }
        });

        connectedSemaphore.await();

        zookeeper.create(path, "123".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + path);
        zookeeper
                .setData(path, "456".getBytes(), -1, new IStatCallback(), null);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IStatCallback implements AsyncCallback.StatCallback {
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println("rc: " + rc + ", path: " + path + ", stat: " + stat);
    }
}


Zookeeper服务框架之Java API的使用(三)_第14张图片

rc(ResultCode)为0,表明成功更新节点数据。

3.6 检测节点是否存在

在调用接口时注册Watcher的话,还可以对节点是否存在进行监听,一旦节点被创建、被删除、数据更新,都会通知客户端。

① 同步方式 

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperNodeExistAPITest {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                try {
                    if (KeeperState.SyncConnected == event.getState()) {
                        if (EventType.None == event.getType()
                                && null == event.getPath()) {
                            connectedSemaphore.countDown();
                        } else if (EventType.NodeCreated == event.getType()) {
                            System.out.println("success create znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true);
                        } else if (EventType.NodeDeleted == event.getType()) {
                            System.out.println("success delete znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true);
                        } else if (EventType.NodeDataChanged == event.getType()) {
                            System.out.println("data changed of znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true);
                        }
                    }
                } catch (Exception e) {
                }
            }
        });

        connectedSemaphore.await();

        zookeeper.exists(path, true);

        zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        zookeeper.setData(path, "123".getBytes(), -1);

        zookeeper.create(path + "/c1", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path + "/c1");

        zookeeper.delete(path + "/c1", -1);
        zookeeper.delete(path, -1);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

 运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第15张图片

结果表明:

  · 无论节点是否存在,都可以通过exists接口注册Watcher。

  · 注册的Watcher,对节点创建、删除、数据更新事件进行监听。

  · 对于指定节点的子节点的各种变化,不会通知客户端。

② 异步方式

package com.npf.test;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperNodeExistAPITest2 {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    static ZooKeeper zookeeper = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zookeeper = new ZooKeeper("npfdev1:2181", 5000, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                try {
                    if (KeeperState.SyncConnected == event.getState()) {
                        if (EventType.None == event.getType()
                                && null == event.getPath()) {
                            connectedSemaphore.countDown();
                        } else if (EventType.NodeCreated == event.getType()) {
                            System.out.println("success create znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true,
                                    new IIStatCallback(), null);
                        } else if (EventType.NodeDeleted == event.getType()) {
                            System.out.println("success delete znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true,
                                    new IIStatCallback(), null);
                        } else if (EventType.NodeDataChanged == event.getType()) {
                            System.out.println("data changed of znode: "
                                    + event.getPath());
                            zookeeper.exists(event.getPath(), true,
                                    new IIStatCallback(), null);
                        }
                    }
                } catch (Exception e) {
                }
            }
        });

        connectedSemaphore.await();

        zookeeper.exists(path, true, new IIStatCallback(), null);

        zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        zookeeper.setData(path, "123".getBytes(), -1);

        zookeeper.create(path + "/c1", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        System.out.println("success create znode: " + path + "/c1");

        zookeeper.delete(path + "/c1", -1);
        zookeeper.delete(path, -1);

        Thread.sleep(Integer.MAX_VALUE);

    }
}

class IIStatCallback implements AsyncCallback.StatCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        System.out.println("rc: " + rc + ", path: " + path + ", stat: " + stat);
    }
}

 运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第16张图片

结果表明当节点不存在时,其rc(ResultCode)为-101。

3.7 权限控制

通过设置Zookeeper服务器上数据节点的ACL控制,就可以对其客户端对该数据节点的访问权限:如果符合ACL控制,则可以进行访问,否则无法访问

① 使用无权限信息的Zookeeper会话访问含权限信息的数据节点 

package com.npf.test;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class AuthSample_Get {
    
    final static String PATH = "/zk-book-auth_test";

    public static void main(String[] args) throws Exception {

        ZooKeeper zookeeper1 = new ZooKeeper("npfdev1:2181", 5000, null);
        zookeeper1.addAuthInfo("digest", "foo:true".getBytes());
        zookeeper1.create(PATH, "init".getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        System.out.println("success create znode: " + PATH);
        ZooKeeper zookeeper2 = new ZooKeeper("npfdev1:2181", 5000, null);
        zookeeper2.getData(PATH, false, null);
    }
}

运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第17张图片

表示权限不够,不能进行操作。

② 删除带权限控制的节点

package com.npf.test;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class AuthSample_Delete {
    final static String PATH = "/zk-book-auth_test";
    final static String PATH2 = "/zk-book-auth_test/child";

    public static void main(String[] args) throws Exception {
        ZooKeeper zookeeper1 = new ZooKeeper("npfdev1:2181", 5000, null);
        zookeeper1.addAuthInfo("digest", "foo:true".getBytes());
        zookeeper1.create(PATH, "init".getBytes(), Ids.CREATOR_ALL_ACL,
                CreateMode.PERSISTENT);

        zookeeper1.create(PATH2, "init".getBytes(), Ids.CREATOR_ALL_ACL,
                CreateMode.EPHEMERAL);

        try {
            ZooKeeper zookeeper2 = new ZooKeeper("npfdev1:2181", 5000, null);
            zookeeper2.delete(PATH2, -1);
        } catch (Exception e) {
            System.out.println("fail to delete: " + e.getMessage());
        }

        ZooKeeper zookeeper3 = new ZooKeeper("npfdev1:2181", 5000, null);
        zookeeper3.addAuthInfo("digest", "foo:true".getBytes());
        zookeeper3.delete(PATH2, -1);
        System.out.println("success delete znode: " + PATH2);

        ZooKeeper zookeeper4 = new ZooKeeper("npfdev1:2181", 5000, null);
        zookeeper4.delete(PATH, -1);
        System.out.println("success delete znode: " + PATH);
    }
}

 运行结果如下:

Zookeeper服务框架之Java API的使用(三)_第18张图片

结果表明若没有权限,则无法删除节点。


你可能感兴趣的:(Zookeeper服务框架之Java API的使用(三))