ZooKeerper学习之Watcher

ZooKeeper为我们提供了用于监视结点变化的Watcher机方法制:

1、可以注册Watcher的方法:getData()、exists()、getChildren()。我们可以通过查看ZooKeeper API看到

getData方法:

 void	getData(String path, boolean watch, AsyncCallback.DataCallback cb, Object ctx)      
 byte[]	getData(String path, boolean watch, Stat stat)      
 void	getData(String path, Watcher watcher, AsyncCallback.DataCallback cb, Object ctx)  
 byte[]	getData(String path, Watcher watcher, Stat stat) 
exists方法:

 Stat	exists(String path, boolean watch) 
          Return the stat of the node of the given path.
 void	exists(String path, boolean watch, AsyncCallback.StatCallback cb, Object ctx) 
          The Asynchronous version of exists.
 Stat	exists(String path, Watcher watcher) 
          Return the stat of the node of the given path.
 void	exists(String path, Watcher watcher, AsyncCallback.StatCallback cb, Object ctx) 
          The Asynchronous version of exists.

getChildren方法:

 List<String>	getChildren(String path, boolean watch) 
          Return the list of the children of the node of the given path.
 void	getChildren(String path, boolean watch, AsyncCallback.Children2Callback cb, Object ctx) 
          The Asynchronous version of getChildren.
 void	getChildren(String path, boolean watch, AsyncCallback.ChildrenCallback cb, Object ctx) 
          The Asynchronous version of getChildren.
 List<String>	getChildren(String path, boolean watch, Stat stat) 
          For the given znode path return the stat and children list.
 List<String>	getChildren(String path, Watcher watcher) 
          Return the list of the children of the node of the given path.
 void	getChildren(String path, Watcher watcher, AsyncCallback.Children2Callback cb, Object ctx) 
          The Asynchronous version of getChildren.
 void	getChildren(String path, Watcher watcher, AsyncCallback.ChildrenCallback cb, Object ctx) 
          The Asynchronous version of getChildren.
 List<String>	getChildren(String path, Watcher watcher, Stat stat) 
          For the given znode path return the stat and children list.

2、可以触发Watcher的方法有:create()、delete()、setData()。通过查看API:

create方法:

 String	create(String path, byte[] data, List<ACL> acl, CreateMode createMode) 
          Create a node with the given path.
 void	create(String path, byte[] data, List<ACL> acl, CreateMode createMode, AsyncCallback.StringCallback cb, Object ctx) 
          The Asynchronous version of create.

delete方法:

 void	delete(String path, int version) 
          Delete the node with the given path.
 void	delete(String path, int version, AsyncCallback.VoidCallback cb, Object ctx) 
          The Asynchronous version of delete.

setData方法:

 Stat	setData(String path, byte[] data, int version) 
          Set the data for the node of the given path if such a node exists and the given version matches the version of the node (if the given version is -1, it matches any node's versions).
 void	setData(String path, byte[] data, int version, AsyncCallback.StatCallback cb, Object ctx) 
          The Asynchronous version of setData.

3、一个Watcher实例是一个回调函数,被调用一次以后就会被移除,如果还需观察结点数据的变化,则还需再次注册Watcher。

4、当我们New ZooKeeper时,注册的Watcher被称为default Watcher,它不是一次性的,只会对client的连接状态变化做出反应。当发生CONNECTIONLOSS之后,只要在session_timeout时间之内能够再次连上(即不发生SESSION_EXPIRED),那么这个连接注册的watcher依然有效。

5、同一个客户端,对某一个节点注册了多次watcher,那么只会收到一次通知。

6、一些操作对应的事件类型:

Event for "/path"

 Event for "/path/child"

Create("/path",...)

 EventType.NodeCreated

/

Delete("/path",...)

EventType.Deleted

/

setData("/path")

EventType.NodeDataChanged

/

Create("/path/child")

EventType.NodeChildrenChanged

EventType.NodeCreated

Delete("/path/child")

EventType.NodeChildrenChanged

EventType.NodeDeleted

setData("/path/child")

/

EventType.NodeDataChanged


7、事件类型与Watcher的对应关系:

event for "/path"

Default watcher

Exists("/path")

getData("/path")

getChildren("/path")

EventType.None

EventType.NodeCreated

EventType.NodeDeleted

EventType.NodeDataChanged

EventType.NodeChildrenChanged


一个小例子:

package org.apache.zookeeper.test;

import java.io.IOException;

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



public class Demo {

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        
    	// 创建一个与服务器的连接
        ZooKeeper zk = new ZooKeeper("192.168.11.201:2181", 6000, new Watcher() {
            // 监控所有被触发的事件
        	/**
        	 * EventType:
        	 * None
        	 * NodeCreated
        	 * NodeChildrenChanged
        	 * NodeDataChanged
        	 * NodeDeleted
        	 */
            public void process(WatchedEvent event) {
                System.out.println("EVENT:" + event.getType());
            }
        });

        // 查看根节点
        System.out.println("ls / => " + zk.getChildren("/", true));

        // 创建一个目录节点
        if (zk.exists("/node", true) == null) {
            zk.create("/node", "this is a znode".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("create /node this is a znode");
            // 查看/node节点数据
            System.out.println("get /node => " + new String(zk.getData("/node", false, null)));
            // 查看根节点
            System.out.println("ls / => " + zk.getChildren("/", true));
        }

        // 创建一个子目录节点
        if (zk.exists("/node/app1", true) == null) {
            zk.create("/node/app1", "this is app1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("create /node/app1 app1");
            // 查看node节点
            System.out.println("ls /node => " + zk.getChildren("/node", true));
        }

        // 修改节点数据
        if (zk.exists("/node", true) != null) {
            zk.setData("/node", "the data is changed".getBytes(), -1);
            // 查看/node节点数据
            System.out.println("get /node => " + new String(zk.getData("/node", false, null)));
        }

        // 删除节点
        if (zk.exists("/node/app1", true) != null) {
            zk.delete("/node/app1", -1);
            zk.delete("/node", -1);
            // 查看根节点
            System.out.println("ls / => " + zk.getChildren("/", true));
        }

        // 关闭连接
        zk.close();
    }
}


         


posted @ 2014-12-18 15:28  ihge2k  阅读(1267)  评论(0编辑  收藏  举报