zookeeper(六)经典案例使用

ZKWatcher.java

  1 package bhz.zookeeper.cluster;
  2 
  3 import java.util.List;
  4 import java.util.Map;
  5 import java.util.concurrent.ConcurrentHashMap;
  6 import java.util.concurrent.CopyOnWriteArrayList;
  7 import java.util.concurrent.CountDownLatch;
  8 
  9 import org.apache.zookeeper.CreateMode;
 10 import org.apache.zookeeper.KeeperException;
 11 import org.apache.zookeeper.WatchedEvent;
 12 import org.apache.zookeeper.Watcher;
 13 import org.apache.zookeeper.Watcher.Event.EventType;
 14 import org.apache.zookeeper.Watcher.Event.KeeperState;
 15 import org.apache.zookeeper.ZooDefs.Ids;
 16 import org.apache.zookeeper.ZooKeeper;
 17 
 18 public class ZKWatcher implements Watcher {
 19 
 20     /** zk变量 */
 21     private ZooKeeper zk = null;
 22     
 23     /** 父节点path */
 24     static final String PARENT_PATH = "/super";
 25     
 26     /** 信号量设置,用于等待zookeeper连接建立之后 通知阻塞程序继续向下执行 */
 27     private CountDownLatch connectedSemaphore = new CountDownLatch(1);
 28     
 29     private List<String> cowaList = new CopyOnWriteArrayList<String>();
 30     
 31     
 32     /** zookeeper服务器地址 */
 33     //public static final String CONNECTION_ADDR = "192.168.80.88:2181,192.168.80.87:2181,192.168.80.86:2181";
 34     public static final String CONNECTION_ADDR = "127.0.0.1:2181";
 35     /** 定义session失效时间 */
 36     public static final int SESSION_TIMEOUT = 30000;
 37     
 38     public ZKWatcher() throws Exception{
 39         zk = new ZooKeeper(CONNECTION_ADDR, SESSION_TIMEOUT, this);
 40         System.out.println("开始连接ZK服务器");
 41         connectedSemaphore.await();
 42     }
 43 
 44 
 45     @Override
 46     public void process(WatchedEvent event) {
 47         // 连接状态
 48         KeeperState keeperState = event.getState();
 49         // 事件类型
 50         EventType eventType = event.getType();
 51         // 受影响的path
 52         String path = event.getPath();
 53         System.out.println("受影响的path : " + path);
 54         
 55         
 56         if (KeeperState.SyncConnected == keeperState) {
 57             // 成功连接上ZK服务器
 58             if (EventType.None == eventType) {
 59                 System.out.println("成功连接上ZK服务器");
 60                 connectedSemaphore.countDown();
 61                 try {
 62                     if(this.zk.exists(PARENT_PATH, false) == null){
 63                         this.zk.create(PARENT_PATH, "root".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);         
 64                     }
 65                     List<String> paths = this.zk.getChildren(PARENT_PATH, true);
 66                     for (String p : paths) {
 67                         System.out.println(p);
 68                         this.zk.exists(PARENT_PATH + "/" + p, true);
 69                     }
 70                 } catch (KeeperException | InterruptedException e) {
 71                     e.printStackTrace();
 72                 }        
 73             } 
 74             //创建节点
 75             else if (EventType.NodeCreated == eventType) {
 76                 System.out.println("节点创建");
 77                 try {
 78                     this.zk.exists(path, true);
 79                 } catch (KeeperException | InterruptedException e) {
 80                     e.printStackTrace();
 81                 }
 82             } 
 83             //更新节点
 84             else if (EventType.NodeDataChanged == eventType) {
 85                 System.out.println("节点数据更新");
 86                 try {
 87                     //update nodes  call function
 88                     this.zk.exists(path, true);
 89                 } catch (KeeperException | InterruptedException e) {
 90                     e.printStackTrace();
 91                 }
 92             } 
 93             //更新子节点
 94             else if (EventType.NodeChildrenChanged == eventType) {
 95                 System.out.println("子节点 ... 变更");
 96                 try {
 97                     List<String> paths = this.zk.getChildren(path, true);
 98                     if(paths.size() >= cowaList.size()){
 99                         paths.removeAll(cowaList);
100                         for(String p : paths){
101                             this.zk.exists(path + "/" + p, true);
102                             //this.zk.getChildren(path + "/" + p, true);
103                             System.out.println("这个是新增的子节点 : " + path + "/" + p);
104                             //add new nodes  call function
105                         }
106                         cowaList.addAll(paths);
107                     } else {
108                         cowaList = paths;
109                     }
110                     System.out.println("cowaList: " + cowaList.toString());
111                     System.out.println("paths: " + paths.toString());
112                     
113                 } catch (KeeperException | InterruptedException e) {
114                     e.printStackTrace();
115                 }
116             } 
117             //删除节点
118             else if (EventType.NodeDeleted == eventType) {
119                 System.out.println("节点 " + path + " 被删除");
120                 try {
121                     //delete nodes  call function
122                     this.zk.exists(path, true);
123                 } catch (KeeperException | InterruptedException e) {
124                     e.printStackTrace();
125                 }
126             }
127             else ;
128         } 
129         else if (KeeperState.Disconnected == keeperState) {
130             System.out.println("与ZK服务器断开连接");
131         } 
132         else if (KeeperState.AuthFailed == keeperState) {
133             System.out.println("权限检查失败");
134         } 
135         else if (KeeperState.Expired == keeperState) {
136             System.out.println("会话失效");
137         }
138         else ;
139 
140         System.out.println("--------------------------------------------");
141     }
142     
143     
144 
145 }

Client1.java

 1 package bhz.zookeeper.cluster;
 2 
 3 import bhz.zookeeper.cluster.ZKWatcher;
 4 
 5 public class Client1 {
 6 
 7     public static void main(String[] args) throws Exception{
 8         
 9         ZKWatcher myWatcher = new ZKWatcher();
10         Thread.sleep(100000000);
11     }
12 }

 

 

Client2.java

 1 package bhz.zookeeper.cluster;
 2 
 3 import bhz.zookeeper.cluster.ZKWatcher;
 4 
 5 public class Client2 {
 6 
 7     public static void main(String[] args) throws Exception{
 8         
 9         ZKWatcher myWatcher = new ZKWatcher();
10         Thread.sleep(100000000);
11     }
12 }

 

 

Test.java

 1 package bhz.zookeeper.cluster;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 
 5 import org.apache.zookeeper.CreateMode;
 6 import org.apache.zookeeper.WatchedEvent;
 7 import org.apache.zookeeper.Watcher;
 8 import org.apache.zookeeper.Watcher.Event.EventType;
 9 import org.apache.zookeeper.Watcher.Event.KeeperState;
10 import org.apache.zookeeper.ZooDefs.Ids;
11 import org.apache.zookeeper.ZooKeeper;
12 
13 public class Test {
14 
15 
16     /** zookeeper地址 */
17     //static final String CONNECT_ADDR = "192.168.1.106:2181,192.168.1.107:2181,192.168.1.108:2181";
18     static final String CONNECT_ADDR = "127.0.0.1:2181";
19     /** session超时时间 */
20     static final int SESSION_OUTTIME = 2000;//ms 
21     /** 信号量,阻塞程序执行,用于等待zookeeper连接成功,发送成功信号 */
22     static final CountDownLatch connectedSemaphore = new CountDownLatch(1);
23     
24     public static void main(String[] args) throws Exception{
25         
26         ZooKeeper zk = new ZooKeeper(CONNECT_ADDR, SESSION_OUTTIME, new Watcher(){
27             @Override
28             public void process(WatchedEvent event) {
29                 //获取事件的状态
30                 KeeperState keeperState = event.getState();
31                 EventType eventType = event.getType();
32                 //如果是建立连接
33                 if(KeeperState.SyncConnected == keeperState){
34                     if(EventType.None == eventType){
35                         //如果建立连接成功,则发送信号量,让后续阻塞程序向下执行
36                         connectedSemaphore.countDown();
37                         System.out.println("zk 建立连接");
38                     }
39                 }
40             }
41         });
42 
43         //进行阻塞
44         connectedSemaphore.await();
45         
46 //        //创建子节点
47 //        zk.create("/super/c1", "c1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
48         //创建子节点
49 //        zk.create("/super/c2", "c2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
50         //创建子节点
51         zk.create("/super/c3", "c3".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
52         //创建子节点
53 //        zk.create("/super/c4", "c4".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
54         
55 //        zk.create("/super/c4/c44", "c44".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
56         
57         //获取节点信息
58 //        byte[] data = zk.getData("/testRoot", false, null);
59 //        System.out.println(new String(data));
60 //        System.out.println(zk.getChildren("/testRoot", false));
61         
62         //修改节点的值
63 //        zk.setData("/super/c1", "modify c1".getBytes(), -1);
64 //        zk.setData("/super/c2", "modify c2".getBytes(), -1);
65 //        byte[] data = zk.getData("/super/c2", false, null);
66 //        System.out.println(new String(data));        
67         
68 //        //判断节点是否存在
69 //        System.out.println(zk.exists("/super/c3", false));
70 //        //删除节点
71 //        zk.delete("/super/c3", -1);
72         
73         
74         
75         
76         
77         
78         
79         
80         zk.close();
81         
82         
83         
84     }
85 }

 

posted @ 2017-10-31 22:41  喻聪  阅读(943)  评论(0编辑  收藏  举报