Zookeeper分布式开发实战------第二梯 初步应用(W

2018-02-21  本文已影响4人  Tango_520f

1.Zookeeper最核心的地方就是watcher,Zk中引入了watcher机制来实现了发布/订阅功能,保证多个节点可以订阅一个主题,主题的状态发生改变时(NodeDataChange,NodeChildrenChange),会通知所有的订阅者;

2.实现watcher的方式:

A.自定义watcher

实现Watcher接口– public class ZLock implements Watcher

public void process(WatchedEvent event),其中even中包含了事件类型(EventType)和通知状态(keeperState);

B.创建zk客户端的时候注册Watcher

ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)

– ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnlyͨ

– ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd)

– ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean

canBeReadOnly)

C.其他API

– getChildren(String path, Watcher watcher)

– getChildren(String path, boolean watch)

• Boolean watch表示是否使用默认的watcher,即创建zk实例时设置的watcher

– getData(String path, boolean watch, Stat stat)

• Boolean watch表示是否使用ЇЈ文中默认的watcher,即创建zk实例时ગ置的watcher

– getData(String path, Watcher watcher, AsyncCallback.DataCallback cb, Object ctx)

– exists(String path, boolean watch)

• Boolean watch表示是否使用ЇЈ文中默认的watcher,即创建zk实例时ગ置的watcher

– exists(String path, Watcher watcher)

3.从源码看Watcher流程

首先:客户端发送请求到服务端时,服务端会被判断是否需要调用wathcer,Servercnxn实现了watcher和stats接口,即包含了连接状态信息和wahtcer的信息,若开启wathcer注册信息,默认dafaultWathcer;

其次:wathcerManager从两个维度维护wathcer,既可从数据节点获取watcher,也可以从watcher中获取数据节点;

阿斯蒂芬、

scheme:其中digest为

上一篇 下一篇

猜你喜欢

热点阅读