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

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

示例代码:

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

调用栈如下图:

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

  1. // void org.I0Itec.zkclient.ZkConnection.connect(Watcher watcher)
  2. public void connect(Watcher watcher) {
  3. _zookeeperLock.lock();
  4. try {
  5. if (_zk != null) {
  6. throw new IllegalStateException("zk client has already been started");
  7. }
  8. try {
  9. LOG.debug("Creating new ZookKeeper instance to connect to " + _servers + ".");
  10. _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher);
  11. } catch (IOException e) {
  12. throw new ZkException("Unable to connect to " + _servers, e);
  13. }
  14. } finally {
  15. _zookeeperLock.unlock();
  16. }
  17. }

ZkClient自身就是一个Watcher:

  1. //省略其他代码
  2. public class ZkClient implements Watcher {
  3. public void process(WatchedEvent event) {
  4. LOG.debug("Received event: " + event);
  5. _zookeeperEventThread = Thread.currentThread();
  6.  
  7. boolean stateChanged = event.getPath() == null;
  8. boolean znodeChanged = event.getPath() != null;
  9. boolean dataChanged = event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated
  10. || event.getType() == EventType.NodeChildrenChanged;
  11.  
  12. getEventLock().lock();
  13. try {
  14.  
  15. // We might have to install child change event listener if a new node was created
  16. if (getShutdownTrigger()) {
  17. LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered");
  18. return;
  19. }
  20. if (stateChanged) {
  21. processStateChanged(event);
  22. }
  23. if (dataChanged) {
  24. processDataOrChildChange(event);
  25. }
  26. } finally {
  27. if (stateChanged) {
  28. getEventLock().getStateChangedCondition().signalAll();
  29.  
  30. // If the session expired we have to signal all conditions, because watches might have been removed and
  31. // there is no guarantee that those
  32. // conditions will be signaled at all after an Expired event
  33. // TODO PVo write a test for this
  34. if (event.getState() == KeeperState.Expired) {
  35. getEventLock().getZNodeEventCondition().signalAll();
  36. getEventLock().getDataChangedCondition().signalAll();
  37. // We also have to notify all listeners that something might have changed
  38. fireAllEvents();
  39. }
  40. }
  41. if (znodeChanged) {
  42. getEventLock().getZNodeEventCondition().signalAll();
  43. }
  44. if (dataChanged) {
  45. getEventLock().getDataChangedCondition().signalAll();
  46. }
  47. getEventLock().unlock();
  48. LOG.debug("Leaving process event");
  49. }
  50. }
  51.  
  52. }

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的值或者子节点改变时,客户端会收到通知:

  1. // ZkClient
  2. public List<String> watchForChilds(final String path) {
  3. if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
  4. throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
  5. }
  6. return retryUntilConnected(new Callable<List<String>>() {
  7. @Override
  8. public List<String> call() throws Exception {
  9. exists(path, true);
  10. try {
  11. return getChildren(path, true);
  12. } catch (ZkNoNodeException e) {
  13. // ignore, the "exists" watch will listen for the parent node to appear
  14. }
  15. return null;
  16. }
  17. });
  18. }
  19.  
  20. public <T> T retryUntilConnected(Callable<T> callable) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException {
  21. if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
  22. throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
  23. }
  24. while (true) {
  25. try {
  26. return callable.call();
  27. } catch (ConnectionLossException e) {
  28. // we give the event thread some time to update the status to 'Disconnected'
  29. Thread.yield();
  30. waitUntilConnected();
  31. } catch (SessionExpiredException e) {
  32. // we give the event thread some time to update the status to 'Expired'
  33. Thread.yield();
  34. waitUntilConnected();
  35. } catch (KeeperException e) {
  36. throw ZkException.create(e);
  37. } catch (InterruptedException e) {
  38. throw new ZkInterruptedException(e);
  39. } catch (Exception e) {
  40. throw ExceptionUtil.convertToRuntimeException(e);
  41. }
  42. }
  43. }

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

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

  1. private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners) {
  2. try {
  3. // reinstall the watch
  4. for (final IZkChildListener listener : childListeners) {
  5. _eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) {
  6.  
  7. @Override
  8. public void run() throws Exception {
  9. try {
  10. // if the node doesn't exist we should listen for the root node to reappear
  11. // 在函数内部,根据是否有listeners,判断加watch
  12. exists(path);
  13. List<String> children = getChildren(path);
  14. listener.handleChildChange(path, children);
  15. } catch (ZkNoNodeException e) {
  16. listener.handleChildChange(path, null);
  17. }
  18. }
  19. });
  20. }
  21. } catch (Exception e) {
  22. LOG.error("Failed to fire child changed event. Unable to getChildren. ", e);
  23. }
  24. }

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

ZkEventThread线程:

  1. class ZkEventThread extends Thread {
  2. private static final Logger LOG = Logger.getLogger(ZkEventThread.class);
  3. private BlockingQueue<ZkEvent> _events = new LinkedBlockingQueue<ZkEvent>();
  4. private static AtomicInteger _eventId = new AtomicInteger(0);
  5.  
  6. static abstract class ZkEvent {
  7. private String _description;
  8. public ZkEvent(String description) {
  9. _description = description;
  10. }
  11. public abstract void run() throws Exception;
  12. @Override
  13. public String toString() {
  14. return "ZkEvent[" + _description + "]";
  15. }
  16. }
  17.  
  18. ZkEventThread(String name) {
  19. setDaemon(true);
  20. setName("ZkClient-EventThread-" + getId() + "-" + name);
  21. }
  22.  
  23. @Override
  24. public void run() {
  25. LOG.info("Starting ZkClient event thread.");
  26. try {
  27. while (!isInterrupted()) {
  28. ZkEvent zkEvent = _events.take();
  29. int eventId = _eventId.incrementAndGet();
  30. LOG.debug("Delivering event #" + eventId + " " + zkEvent);
  31. try {
  32. zkEvent.run();
  33. } catch (InterruptedException e) {
  34. interrupt();
  35. } catch (ZkInterruptedException e) {
  36. interrupt();
  37. } catch (Throwable e) {
  38. LOG.error("Error handling event " + zkEvent, e);
  39. }
  40. LOG.debug("Delivering event #" + eventId + " done");
  41. }
  42. } catch (InterruptedException e) {
  43. LOG.info("Terminate ZkClient event thread.");
  44. }
  45. }
  46.  
  47. public void send(ZkEvent event) {
  48. if (!isInterrupted()) {
  49. LOG.debug("New event: " + event);
  50. _events.add(event);
  51. }
  52. }
  53. }

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. loj10009 P1717 钓鱼

    P1717 钓鱼 贪心+优先队列 先枚举最后走到哪个湖,然后用优先队列跑一遍贪心即可 #include<iostream> #include<cstdio> #include& ...

  2. 02: tornado进阶篇

    目录:Tornado其他篇 01: tornado基础篇 02: tornado进阶篇 03: 自定义异步非阻塞tornado框架 04: 打开tornado源码剖析处理过程 目录: 1.1 自定制t ...

  3. 基于qml创建最简单的图像处理程序(1)-基于qml创建界面

    <基于qml创建最简单的图像处理程序>系列课程及配套代码基于qml创建最简单的图像处理程序(1)-基于qml创建界面http://www.cnblogs.com/jsxyhelu/p/83 ...

  4. windows 常用快捷键和dos命令

    快捷键 win + R 打开dos命令行窗口 win + E 打开资源管理窗口 (计算机) shift + 鼠标右击 + select 在此处打开命令窗口 可在资源管理目录下打开dos命令 windo ...

  5. getContext,getApplicationContext和this有什么区别

    使用this, 说明当前类是context的子类,一般是activity application等使用getApplicationContext 取得的是当前app所使用的application,这在 ...

  6. Python3基础 os.path.dirname 对路径字符串进行处理 返回所在文件夹的路径

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  7. LTE-A 载波聚合(Carrier Aggregation)介绍【转】

    本文转自:https://blog.csdn.net/txgc1009/article/details/46467255 载波聚合(Carrier Aggregation) 首先介绍几个基本概念 Pr ...

  8. C#预处理器指令【转】

    本文转载自:http://www.cnblogs.com/miffylf/p/4005223.html C#有许多名为预处理器指令的命令.这些命令从来不会转化为可执行代码中的命令,但会影响编译过程的各 ...

  9. ubuntu下交叉编译ffmpeg

    环境:ubuntu16.04 交叉编译器版本:4.8.3 依赖x264,lame x264: 1.wget ftp://ftp.videolan.org/pub/x264/snapshots/last ...

  10. 李白打酒|2014年蓝桥杯B组题解析第三题-fishers

    李白打酒 话说大诗人李白,一生好饮.幸好他从不开车. 一天,他提着酒壶,从家里出来,酒壶中有酒2斗.他边走边唱: 无事街上走,提壶去打酒. 逢店加一倍,遇花喝一斗. 这一路上,他一共遇到店5次,遇到花 ...