您的位置:首页 > 运维架构

Zookeeper之Curator(1)客户端对节点的一些监控事件的api使用

2017-04-28 18:53 477 查看
《一》节点改变事件的监听

1 public class CauratorClientTest {
2
3     //链接地址
4     private static  String zkhost="172.19.27.246:2181";
5     //sessionTimeoutMs会话超时时间,单位为毫秒。默认是60000ms
6     private static  int  sessionTimeoutMs=5000;
7     //connectionTimeoutMs连接创建超时时间,单位毫秒,默认15000ms
8     private static  int connectionTimeOutMs=3000;
9     //重连策略
10     private static  int maxRetries;
11     //    zookeeper连接间隔时间基数
12     private static int baseSleepTimeMs=1000;
13     //系统域dev,qa,pro
14     private static String domain="dev";
15
16
17     /**
18  * 数据节点被改变的事件。能监听节点存储的数据发生变化,和节点被删除的事件。
19  * 节点被删除后,会调用回调方法。
20  */
21 public static void testNodeChangeEvent() throws Exception{
22     CuratorFramework client = CuratorFrameworkFactory.newClient(zkhost,sessionTimeoutMs,connectionTimeOutMs, new ExponentialBackoffRetry(baseSleepTimeMs,maxRetries));
23     client.start();
24
25     String path=client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/dev/sxf/cd","sxf".getBytes());
26
27     NodeCache nodeCache=new NodeCache(client,path);
28
29     /**
30      * 注册数据节点中存储的数据被改变的事件
31      */
32     nodeCache.getListenable().addListener(new NodeCacheListener() {
33         /**
34          * 数据节点变化事件
35          */
36         @Override
37         public void nodeChanged() throws Exception {
38
39             ChildData data=nodeCache.getCurrentData();
40             if(data==null){
41                 System.out.println("节点被删除");
42                 return;
43             }
44
45             Stat  stat=data.getStat();
46
47             int a=stat.getNumChildren();
48
49             System.out.println("子节点的个数为==>"+a);
50
51             System.out.println("节点数据被改变改变后的数值为==>"+new String(nodeCache.getCurrentData().getData()));
52
53         }
54     });
55
56     nodeCache.start();
57
58
59     //当前线程休眠几秒
60     Thread.sleep(10000L);
61
62
63     client.setData().forPath("/dev/sxf/cd","中国人民解放军".getBytes());
64
65
66     //当前线程休眠几秒
67     Thread.sleep(10000L);
68     client.setData().forPath("/dev/sxf/cd","第二次改变".getBytes());
69
70
71     //当前线程休眠几秒
72     Thread.sleep(10000L);
73     client.delete().forPath("/dev/sxf/cd");
74
75
76
77     Thread.sleep(100000L);
78
79 }
80
81 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: