zookeeper 的监听通知机制

zookeeper的监听通知机制:

      客户端注册监听它关心的目录节点,当目录节点发生变化(数据改变、被删除、子目录节点增加删除)时,zookeeper会通知客户端

一、先启动一个本地zookeeper, 默认端口 2181

  

二、创建一个节点 /mynode 并设置初始值为 node1

  

三、用Java API 来操作

  ① 先引入 pom 

    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.12</version>
    </dependency>

   ② 具体代码

package com.ceair.mutms;

import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperSync implements Watcher{

	private static CountDownLatch  countDownLatch  = new CountDownLatch(1);
	private static ZooKeeper zk = null;
	private static Stat stat = new Stat();
	
	public static void main(String[] args) throws Exception {
		// 节点路径
		String path = "/mynode";
		// 连接zookeeper
		zk = new ZooKeeper("10.68.155.114:2181", 5000, new ZookeeperSync());
		countDownLatch.await();
		String str = new String(zk.getData(path, true, stat));
		System.out.println("原始数据为:" + str);
		Thread.sleep(1000);
	}
	
	@Override
	public void process(WatchedEvent event) {
		if (KeeperState.SyncConnected == event.getState()) {
			System.out.println("zk连接成功通知");
			if (EventType.None == event.getType() && null == event.getPath()) {
				countDownLatch.countDown();
			} else if (event.getType() == EventType.NodeDataChanged) {
				try {
					String str = new String(zk.getData(event.getPath(), true, stat));
					System.out.println("数据已修改,新值为:" + str);
				} catch (Exception e) {
					
				}
			}
		}
	}
}

  ③ 启动代码, 并把数据改为node2

    

   结果:

zk连接成功通知
原始数据为:node1
zk连接成功通知
数据已修改,新值为:node2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值