dubbo使用的zk客户端
在使用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客户端的更多相关文章
- 查看Dubbo服务-通过zk客户端
一.基本概念 https://www.cnblogs.com/huasky/p/8268568.html 二.下载与安装 1.进入要下载的版本的目录,选择.tar.gz文件下载 下载链接:http:/ ...
- ZK客户端脚本的简单使用
sh zkCli.sh [-server ip:port] :连接节点zk客户端[-server ip:port 用于连接集群中指定节点的客户端] 1.创建节点 create [-s] [-e] pa ...
- zk客户端的ClientCnxn类
ClientCnxn是客户端的类:该类管理zk客户端的socket io,维持一个可用服务器的列表. //ClientCnxn类 private final LinkedList<Packet& ...
- 利用zk客户端删除solr shard
进入zk客户端 ./bin/zkCli.sh -server ip:2181 显示所有的内容: ls / 删除数据: rmr /filename path
- 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习
第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-1 zookeeper常用命令行操作 4-2 session的基本原理与create命令的使用
- zk客户端及锁的使用
1.生成zk客户端对象 private CuratorFramework buildClient() { logger.info("zookeeper registry center ini ...
- ZK客户端
说明:本文为读<从Paxos到Zookeeper 分布式一致性原理与实践>读书笔记 shell操作 Java客户端 原始API pom文件: <dependency> < ...
- 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-2 session的基本原理与create命令的使用
客户端与服务端之间存在的连接,那么这样的一个连接我们就称之为会话,也就是session.其实就相当于是我们在做JSP或者说是Service的时候,那么服务端是Servlet,客户端使用的是浏览器.浏览 ...
- 第4章 ZK基本特性与基于Linux的ZK客户端命令行学习 4-1 zookeeper常用命令行操作
ls path [watch] watch是一个监督者.quota是zookeeper的子目录.目录就是节点的意思,对于zookeeper来说它是以一个节点来说的,所以说/就是根节点,zookeepe ...
随机推荐
- Json解析类
Json解析类 定义两个辅助类 public class JSONObject : Dictionary<string, object> { } public class JSONAr ...
- 20145322何志威《网络对抗技术》Exp6 信息搜集技术
20145322何志威<网络对抗技术>Exp6 信息搜集技术 实验内容 掌握信息搜集的最基础技能: (1)各种搜索技巧的应用 (2)DNS IP注册信息的查询 (3)基本的扫描技术:主机发 ...
- 2017.11.11 B201 练习题思路及解题方法
2017.11.11 B201 练习题思路及解题方法 题目类型及涵盖知识点 本次总共有6道题目,都属于MISC分类的题目,涵盖的知识点有 信息隐藏 暴力破解 音轨,摩斯电码 gif修改,base64原 ...
- payload
payload就是协议报文中的有效载荷所占报文的百分比,用报文中去除协议的长度/报文总长度,协议设计的时候需要考虑到有效载荷所占的比重,避免出现payload很小的情况,比如TCP在设计的时候,就考虑 ...
- VC++开机自动启动程序的几种方法 (转载)
转载:http://blog.csdn.net/zhazhiqiang/article/details/51909703 很多监控软件要求软件能够在系统重新启动后不用用户去点击图标启动项目,而是直接能 ...
- Python3基础 __len__,__getitem__ 记录列表中元素访问的次数 定制不可变序列,下标字典
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- linux下安装微信小程序开发工具
一.环境:: ubuntu 16.04 二.安装过程: 2.1 安装wine sudo apt-get install wine 2.2 安装nwjs-sdk 2.2.1 下载linux版nwjs-s ...
- 【Python】【fmt】
[练习] #练习1:format print(format(3.44444,'.3e')) #3.444e+00 #练习2:findall() & finditer()import ...
- codeforces 766E Mahmoud and a xor trip
题目链接:http://codeforces.com/problemset/problem/766/E 大意,给出一个$n$个点的树,每个点都有一个权值,令$Disx$为$u$到$v$路径上的异或和求 ...
- Python matplot画柱状图(一)
图的存在,让数据变得形象化.无论多么复杂的东西,都是简单的组合. import matplotlib.pyplot as plt import numpy as np dict = {'A': 40, ...