在使用dubbo的过程中,当注册中心的数据修改后,新的配置是怎样刷到consumer和provider的?本文以consumer为例,进行分析。

dubbo使用的是zkclient的jar,而zkclient依赖zookeeper的jar。

示例代码:

public class MyI0zk {
public static void main(String[] args) {
ZkClient zkclient = new ZkClient("127.0.0.1:2181");
int countChildren = zkclient.countChildren("/");
System.out.println(countChildren);
}
}

调用栈如下图:

在connect方法中创建了ZooKeeper对象:

// void org.I0Itec.zkclient.ZkConnection.connect(Watcher watcher)
public void connect(Watcher watcher) {
_zookeeperLock.lock();
try {
if (_zk != null) {
throw new IllegalStateException("zk client has already been started");
}
try {
LOG.debug("Creating new ZookKeeper instance to connect to " + _servers + ".");
_zk = new ZooKeeper(_servers, _sessionTimeOut, watcher);
} catch (IOException e) {
throw new ZkException("Unable to connect to " + _servers, e);
}
} finally {
_zookeeperLock.unlock();
}
}

ZkClient自身就是一个Watcher:

//省略其他代码
public class ZkClient implements Watcher {
public void process(WatchedEvent event) {
LOG.debug("Received event: " + event);
_zookeeperEventThread = Thread.currentThread(); boolean stateChanged = event.getPath() == null;
boolean znodeChanged = event.getPath() != null;
boolean dataChanged = event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated
|| event.getType() == EventType.NodeChildrenChanged; getEventLock().lock();
try { // We might have to install child change event listener if a new node was created
if (getShutdownTrigger()) {
LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered");
return;
}
if (stateChanged) {
processStateChanged(event);
}
if (dataChanged) {
processDataOrChildChange(event);
}
} finally {
if (stateChanged) {
getEventLock().getStateChangedCondition().signalAll(); // If the session expired we have to signal all conditions, because watches might have been removed and
// there is no guarantee that those
// conditions will be signaled at all after an Expired event
// TODO PVo write a test for this
if (event.getState() == KeeperState.Expired) {
getEventLock().getZNodeEventCondition().signalAll();
getEventLock().getDataChangedCondition().signalAll();
// We also have to notify all listeners that something might have changed
fireAllEvents();
}
}
if (znodeChanged) {
getEventLock().getZNodeEventCondition().signalAll();
}
if (dataChanged) {
getEventLock().getDataChangedCondition().signalAll();
}
getEventLock().unlock();
LOG.debug("Leaving process event");
}
} }

1. 再看看dubbo的consumer创建ZkClient的调用栈:

2. consumer的ZkClient注册childListener,等待节点内容改变的通知,对[/dubbo/com.zhang.HelloService/providers, /dubbo/com.zhang.HelloService/configurators, /dubbo/com.zhang.HelloService/routers]分别进行注册:

实际调用exists和getChildren方法,对应zk的stat path watch和ls path watch命令,即当/dubbo/com.zhang.HelloService/providers的值或者子节点改变时,客户端会收到通知:

// ZkClient
public List<String> watchForChilds(final String path) {
if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
}
return retryUntilConnected(new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
exists(path, true);
try {
return getChildren(path, true);
} catch (ZkNoNodeException e) {
// ignore, the "exists" watch will listen for the parent node to appear
}
return null;
}
});
} public <T> T retryUntilConnected(Callable<T> callable) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
}
while (true) {
try {
return callable.call();
} catch (ConnectionLossException e) {
// we give the event thread some time to update the status to 'Disconnected'
Thread.yield();
waitUntilConnected();
} catch (SessionExpiredException e) {
// we give the event thread some time to update the status to 'Expired'
Thread.yield();
waitUntilConnected();
} catch (KeeperException e) {
throw ZkException.create(e);
} catch (InterruptedException e) {
throw new ZkInterruptedException(e);
} catch (Exception e) {
throw ExceptionUtil.convertToRuntimeException(e);
}
}
}

3. consumer收到通知,重新加watch

consumer的ZkClient收到通知后,会将通知包装成ZkEvent事件,发送给ZkEventThread,ZkEvent的run方法里重新地加上watch:

private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners) {
try {
// reinstall the watch
for (final IZkChildListener listener : childListeners) {
_eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) { @Override
public void run() throws Exception {
try {
// if the node doesn't exist we should listen for the root node to reappear
// 在函数内部,根据是否有listeners,判断加watch
exists(path);
List<String> children = getChildren(path);
listener.handleChildChange(path, children);
} catch (ZkNoNodeException e) {
listener.handleChildChange(path, null);
}
}
});
}
} catch (Exception e) {
LOG.error("Failed to fire child changed event. Unable to getChildren. ", e);
}
}

4. 从ZkEvent的run方法进入,刷新配置:

ZkEventThread线程:

class ZkEventThread extends Thread {
private static final Logger LOG = Logger.getLogger(ZkEventThread.class);
private BlockingQueue<ZkEvent> _events = new LinkedBlockingQueue<ZkEvent>();
private static AtomicInteger _eventId = new AtomicInteger(0); static abstract class ZkEvent {
private String _description;
public ZkEvent(String description) {
_description = description;
}
public abstract void run() throws Exception;
@Override
public String toString() {
return "ZkEvent[" + _description + "]";
}
} ZkEventThread(String name) {
setDaemon(true);
setName("ZkClient-EventThread-" + getId() + "-" + name);
} @Override
public void run() {
LOG.info("Starting ZkClient event thread.");
try {
while (!isInterrupted()) {
ZkEvent zkEvent = _events.take();
int eventId = _eventId.incrementAndGet();
LOG.debug("Delivering event #" + eventId + " " + zkEvent);
try {
zkEvent.run();
} catch (InterruptedException e) {
interrupt();
} catch (ZkInterruptedException e) {
interrupt();
} catch (Throwable e) {
LOG.error("Error handling event " + zkEvent, e);
}
LOG.debug("Delivering event #" + eventId + " done");
}
} catch (InterruptedException e) {
LOG.info("Terminate ZkClient event thread.");
}
} public void send(ZkEvent event) {
if (!isInterrupted()) {
LOG.debug("New event: " + event);
_events.add(event);
}
}
}

dubbo使用的zk客户端的更多相关文章

  1. 查看Dubbo服务-通过zk客户端

    一.基本概念 https://www.cnblogs.com/huasky/p/8268568.html 二.下载与安装 1.进入要下载的版本的目录,选择.tar.gz文件下载 下载链接:http:/ ...

  2. ZK客户端脚本的简单使用

    sh zkCli.sh [-server ip:port] :连接节点zk客户端[-server ip:port 用于连接集群中指定节点的客户端] 1.创建节点 create [-s] [-e] pa ...

  3. zk客户端的ClientCnxn类

    ClientCnxn是客户端的类:该类管理zk客户端的socket io,维持一个可用服务器的列表. //ClientCnxn类 private final LinkedList<Packet& ...

  4. 利用zk客户端删除solr shard

    进入zk客户端 ./bin/zkCli.sh -server ip:2181 显示所有的内容: ls / 删除数据: rmr /filename path

  5. 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习

    第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-1 zookeeper常用命令行操作 4-2 session的基本原理与create命令的使用

  6. zk客户端及锁的使用

    1.生成zk客户端对象 private CuratorFramework buildClient() { logger.info("zookeeper registry center ini ...

  7. ZK客户端

    说明:本文为读<从Paxos到Zookeeper 分布式一致性原理与实践>读书笔记 shell操作 Java客户端 原始API pom文件: <dependency> < ...

  8. 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-2 session的基本原理与create命令的使用

    客户端与服务端之间存在的连接,那么这样的一个连接我们就称之为会话,也就是session.其实就相当于是我们在做JSP或者说是Service的时候,那么服务端是Servlet,客户端使用的是浏览器.浏览 ...

  9. 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-1 zookeeper常用命令行操作

    ls path [watch] watch是一个监督者.quota是zookeeper的子目录.目录就是节点的意思,对于zookeeper来说它是以一个节点来说的,所以说/就是根节点,zookeepe ...

随机推荐

  1. bzoj1638 / P2883 [USACO07MAR]牛交通Cow Traffic

    P2883 [USACO07MAR]牛交通Cow Traffic 对于每一条边$(u,v)$ 设入度为0的点到$u$有$f[u]$种走法 点$n$到$v$(通过反向边)有$f2[v]$种走法 显然经过 ...

  2. P3294 [SCOI2016]背单词

    P3294 [SCOI2016]背单词 Trie+贪心 倒插进树+取出重建+子树处理+贪心遍历 倒插进树:把后缀转化为前缀,所以把字符串倒着插进Trie中 取出重建:重新建立一棵以单词为节点的树,如果 ...

  3. P4289 [HAOI2008]移动玩具(bfs)

    P4289 [HAOI2008]移动玩具 双向bfs+状态压缩+记忆化搜索 双向bfs用于对bfs的优化,每次找到可扩展节点少的一边进行一次bfs,找到的第一个互相接触的点即为最短路径 矩阵范围仅4* ...

  4. c++ 11和java 8都支持lambda表达式

    c++ 11居然都支持lambda表达式了,看了这确实是有必要了. 具体可见http://www.cprogramming.com/c++11/c++11-lambda-closures.html

  5. Android http通信案例

    Android studio 编写安卓程序,实现 http 通信,获得百度主页源代码. -------------------------------------------------------- ...

  6. VC++ 文件和应用程序关联,默认图标不显示问题

  7. 解决Duilib集成CEF浏览器在Win10无法向客户区拖拽文件

    在Duilib中集成CEF浏览器项目实际开发中,遇到一个问题. 一个需求从资源管理器(桌面)拖拽文件到客户端,窗口捕获WM_DROPFILES消息然后进行消息处理,但客户区是集成的CEF浏览器,浏览器 ...

  8. C#调用托管ocx、dll

    前篇文章是调用非托管,比较复杂,这里是调用托管,很简单[所以在遇到非托管dll时可以通过二次封装成托管的方式,再通过这边文章来使用] 1.注意这是基于COM的ocx或者dll,所以用regsvr32先 ...

  9. Go第十篇之反射

    反射是指在程序运行期对程序本身进行访问和修改的能力.程序在编译时,变量被转换为内存地址,变量名不会被编译器写入到可执行部分.在运行程序时,程序无法获取自身的信息. 支持反射的语言可以在程序编译期将变量 ...

  10. 【转载】Multiboot规范

    转自:Multiboot规范 Multiboot规范 本文定义了Multiboot规范--提议中的引导过程标准.本文是此规范的0.6.93版. Multiboot规范简介 本章描述了一些关于Multi ...