使用 ZooKeeper 同步集群配置

用 ZooKeeper 同步集群配置,当需要修改所有节点配置时,将配置更新到 ZooKeeper 的一个节点,引起这个节点数据发生变化,

其他所有需要同步配置的节点上的本地 Watcher 会立即发现节点状态的变化,并将最新数据更新到本地

官方Demo 改了改,响应 Watcher 时用 ConfFileUtil 更新一下本地配置就可以了

  1. public class Executor implements Watcher, Runnable,  
  2.         DataMonitor.DataMonitorListener {  
  3.   
  4.     String znode;  
  5.     DataMonitor dm;  
  6.     ZooKeeper zk;  
  7.     String filename;  
  8.   
  9.     public Executor(String hostPort, String znode, String filename)  
  10.             throws KeeperException, IOException {  
  11.         this.filename = filename;  
  12.         zk = new ZooKeeper(hostPort, 3000, this);  
  13.         dm = new DataMonitor(zk, znode, this);  
  14.     }  
  15.   
  16.     public static void main(String[] args) {  
  17.         args = new String[3];  
  18.         args[0] = Constant.ZKPEER;  
  19.         args[1] = Constant.ZNODE;  
  20.         args[2] = "";  
  21.         String hostPort = args[0];  
  22.         String znode = args[1];  
  23.         String filename = args[2];  
  24.         try {  
  25.             new Executor(hostPort, znode, filename).run();  
  26.         } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30.   
  31.     public void process(WatchedEvent event) {  
  32.         dm.process(event);  
  33.     }  
  34.   
  35.     public void run() {  
  36.         try {  
  37.             synchronized (this) {  
  38.                 while (!dm.dead) {  
  39.                     wait();  
  40.                 }  
  41.             }  
  42.         } catch (InterruptedException e) {  
  43.         }  
  44.     }  
  45.   
  46.     public void closing(int rc) {  
  47.         synchronized (this) {  
  48.             notifyAll();  
  49.         }  
  50.     }  
  51.   
  52.     /** 
  53.      * 处理数据 
  54.      */  
  55.     public void exists(byte[] data) {  
  56.   
  57.         System.out.println("...Invoked:Executor.exists(byte[] data)...");  
  58.         ConfFileUtil.sync(data);  
  59.     }  
  60. }  

上面的 Executor 用来和 znode 建立和维护连接

DataMonitor 仍旧负责接收事件 处理结果,这个类基本没改。

触发 Watcher 时, DataMonitor 委托 Executor 来更新本地配置

完整代码见 GITHUB

更新节点时需注意一点

  1. zk.setData(Constant.ZNODE, bytes, -1, null, null);  


这个 byte[] 是有大小限制的,并且如果它超过了限制,ZooKeeper 也不会告诉你,官方文档说的是 1M,这个我没测试

当更新数据不成功且没有任何异常时,就需要检查这个数组是不是太长了 

原文地址:https://www.cnblogs.com/fx2008/p/4156066.html