zookeeper笔记

import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest {
	@Autowired
	ZKManager zKManager;
	@Test
	public void test() {
		try {
			String path = "/famliy";
			byte[] data = "Famliy.Lee".getBytes();
			//zKManager.zk.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			zKManager.zk.create(path+"/thomas", "thomas".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			zKManager.zk.create(path+"/ellen", "ellen".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			zKManager.zk.delete(path+"/thomas", -1);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class ZKManager implements Watcher {
	 private String hostPort="127.0.0.1:2181";
	 private int timeOut=20000;
	 private String path="/famliy";
	 public ZooKeeper zk;
	public ZKManager() throws IOException{
		zk = new ZooKeeper(hostPort,timeOut,this);
	}
	public void process(WatchedEvent event) {
		System.out.println("/test is change: type="+event.getType()+" | state="+event.getState());
		try {
			List<String> zNodes=zk.getChildren(path, this);
			if(null!=zNodes){
				for(String zNode : zNodes){
					System.out.println("zNode="+zNode);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

 

执行结果:

/test is change: type=None | state=SyncConnected
zNode=thomas
/test is change: type=NodeChildrenChanged | state=SyncConnected
zNode=ellen
zNode=thomas
/test is change: type=NodeChildrenChanged | state=SyncConnected
zNode=ellen

 

 

 ZKManager 负责创建zookeeper链接。

注:

getChildren getData监控变化,不过只能使用一次 。如果想持续监控的话每次都重新调用这些方法。

zk.getChildren(path, this );监控子目录的变化,this是一个Watcher(在这里时ZKManager),这样当zookeeper相关路径下的东西改变后就会调用ZKManager的process方法来通知client。

getChildren("/family",this ) ZKManager负责watch family 下子节点的状态,当有变化时调用自己的process方法

getData("/family",this)ZKManager负责watch family自己数据的状态,有变化时调用自己的process方法

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值