如果要使用类似Wather的监听功能Curator必须依赖一个jar包,Maven依赖,

<dependency>
  <groupId>org.apache.curator</groupId>
  <artifactId>curator-recipes</artifactId>
  <version>4.0.0</version>
</dependency>

有了这个依赖包,我们使用NodeCache的方式去客户端实例中注册一个监听缓存,然后实现对应的监听方法即可,这里主要有两种监听方式

NodeCacheListener:监听节点的新增,修改操作。

 1 package bjsxt.curator.watcher;
 2 
 3 import org.apache.curator.RetryPolicy;
 4 import org.apache.curator.framework.CuratorFramework;
 5 import org.apache.curator.framework.CuratorFrameworkFactory;
 6 import org.apache.curator.framework.recipes.cache.NodeCache;
 7 import org.apache.curator.framework.recipes.cache.NodeCacheListener;
 8 import org.apache.curator.retry.ExponentialBackoffRetry;
 9 
10 public class CuratorWatcher1 {
11 
12     /** zookeeper地址 */
13     static final String CONNECT_ADDR = "192.168.2.2:2181";
14     /** session超时时间 */
15     static final int SESSION_OUTTIME = 5000;// ms
16 
17     public static void main(String[] args) throws Exception {
18 
19         // 1 重试策略:初试时间为1s 重试10次
20         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
21         // 2 通过工厂创建连接
22         CuratorFramework cf = CuratorFrameworkFactory.builder()
23                 .connectString(CONNECT_ADDR).sessionTimeoutMs(SESSION_OUTTIME)
24                 .retryPolicy(retryPolicy).build();
25 
26         // 3 建立连接
27         cf.start();
28 
29         // 4 建立一个cache缓存 第三个参数代表是否压缩
30         final NodeCache cache = new NodeCache(cf, "/super", false);
31         cache.start(true);
32         cache.getListenable().addListener(new NodeCacheListener() {
33             /**
34              * <B>方法名称:</B>nodeChanged<BR>
35              * <B>概要说明:</B>触发事件为创建节点和更新节点,在删除节点的时候并不触发此操作。<BR>
36              * 
37              * @see org.apache.curator.framework.recipes.cache.NodeCacheListener#nodeChanged()
38              */
39             @Override
40             public void nodeChanged() throws Exception {
41                 System.out.println("路径为:" + cache.getCurrentData().getPath());
42                 System.out.println("数据为:"
43                         + new String(cache.getCurrentData().getData()));
44                 System.out.println("状态为:" + cache.getCurrentData().getStat());
45                 System.out.println("---------------------------------------");
46             }
47         });
48 
49         Thread.sleep(1000);
50         cf.create().forPath("/super", "123".getBytes());
51 
52         Thread.sleep(1000);
53         cf.setData().forPath("/super", "456".getBytes());
54 
55         Thread.sleep(1000);
56         cf.delete().forPath("/super");
57 
58         Thread.sleep(Integer.MAX_VALUE);
59 
60     }
61 }


PathChildrenCacheListener:监听子节点的新增,修改,删除操作。

 1 package bjsxt.curator.watcher;
 2 
 3 import org.apache.curator.RetryPolicy;
 4 import org.apache.curator.framework.CuratorFramework;
 5 import org.apache.curator.framework.CuratorFrameworkFactory;
 6 import org.apache.curator.framework.recipes.cache.PathChildrenCache;
 7 import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
 8 import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
 9 import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
10 import org.apache.curator.retry.ExponentialBackoffRetry;
11 
12 public class CuratorWatcher2 {
13 
14     /** zookeeper地址 */
15     static final String CONNECT_ADDR = "192.168.2.2:2181";
16     /** session超时时间 */
17     static final int SESSION_OUTTIME = 5000;// ms
18 
19     public static void main(String[] args) throws Exception {
20 
21         // 1 重试策略:初试时间为1s 重试10次
22         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
23         // 2 通过工厂创建连接
24         CuratorFramework cf = CuratorFrameworkFactory.builder()
25                 .connectString(CONNECT_ADDR).sessionTimeoutMs(SESSION_OUTTIME)
26                 .retryPolicy(retryPolicy).build();
27 
28         // 3 建立连接
29         cf.start();
30 
31         // 4 建立一个PathChildrenCache缓存,第三个参数为是否接受节点数据内容 如果为false则不接受
32         PathChildrenCache cache = new PathChildrenCache(cf, "/super", true);
33         // 5 在初始化的时候就进行缓存监听
34         cache.start(StartMode.POST_INITIALIZED_EVENT);
35         cache.getListenable().addListener(new PathChildrenCacheListener() {
36             /**
37              * <B>方法名称:</B>监听子节点变更<BR>
38              * <B>概要说明:</B>新建、修改、删除<BR>
39              * 
40              * @see org.apache.curator.framework.recipes.cache.PathChildrenCacheListener#childEvent(org.apache.curator.framework.CuratorFramework,
41              *      org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)
42              */
43             @Override
44             public void childEvent(CuratorFramework cf,
45                     PathChildrenCacheEvent event) throws Exception {
46                 switch (event.getType()) {
47                 case CHILD_ADDED:
48                     System.out.println("CHILD_ADDED :"
49                             + event.getData().getPath());
50                     break;
51                 case CHILD_UPDATED:
52                     System.out.println("CHILD_UPDATED :"
53                             + event.getData().getPath());
54                     break;
55                 case CHILD_REMOVED:
56                     System.out.println("CHILD_REMOVED :"
57                             + event.getData().getPath());
58                     break;
59                 default:
60                     break;
61                 }
62             }
63         });
64 
65         // 创建本身节点不发生变化
66         cf.create().forPath("/super", "init".getBytes());
67 
68         // 添加子节点
69         Thread.sleep(1000);
70         cf.create().forPath("/super/c1", "c1内容".getBytes());
71         Thread.sleep(1000);
72         cf.create().forPath("/super/c2", "c2内容".getBytes());
73 
74         // 修改子节点
75         Thread.sleep(1000);
76         cf.setData().forPath("/super/c1", "c1更新内容".getBytes());
77 
78         // 删除子节点
79         Thread.sleep(1000);
80         cf.delete().forPath("/super/c2");
81 
82         // 删除本身节点
83         Thread.sleep(1000);
84         cf.delete().deletingChildrenIfNeeded().forPath("/super");
85 
86         Thread.sleep(Integer.MAX_VALUE);
87 
88     }
89 }

 

posted on 2018-05-31 16:33  小~虎  阅读(652)  评论(0编辑  收藏  举报