zookeeper3.3.3初探【安装+APIs创建一个znode】
zookeeper安装很简单
1、下载http://mirror.bit.edu.cn/apache/zookeeper/
2、解压tar -xzvf zookeeper-3.3.5.tar.gz
3、vim ~/.bashrc中添加环境变量
export ZOOKEEPER_HOME=/home/ckl/hadoop-0.20.2/zookeeper
export PATH=$PATH:$ZOOKEEPER_HOME
4、修改zookeeper/conf/下的zoo.cfg(这个文件由zoo_sample.cfg重命名而来)
tickTime=5000
dataDir=/home/ckl/hadoop-0.20.2/zookeeper/data
clientPort=2181
5、重启终端,执行zk_Server.sh start
6、成功启动后执行zkCli.sh
7、下面利用eclipse新建一个工程zkTest,导入zookeeper下的jarAPI包,新建一个class ConnectionWatcher 用于连接zookeeper
import java.util.List;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.ZooDefs.Ids;public class ZnodesManage extends ConnectionWatcher{/** * 创建znode */public void create(String groupName)throws KeeperException,InterruptedException{String path="/"+groupName;String createdPath=zk.create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("Created "+createdPath);}/** * 创建子znode */public void join(String groupName,String memberName)throws KeeperException,InterruptedException{String path="/"+groupName+"/"+memberName;//类似于创建子目录String createPath=zk.create(path, null,Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);//永久znode,若为EPHEMERAL则当前会话结束(程序运行完)会create的znode也会删除System.out.println("Created "+createPath);}public void list(String groupName)throws KeeperException,InterruptedException{String path="/"+groupName;try{List<String>children=zk.getChildren(path, false);//获取子znode列表System.out.println(children.size());if(children.isEmpty()){System.out.printf("%s中没有子znode\n",groupName);System.exit(1);}for(String child : children){System.out.println(child);}}catch (KeeperException.NoNodeException e) {// TODO: handle exceptionSystem.out.printf("%s znode不存在",groupName);System.exit(1);}}public static void main(String[]args)throws Exception{ZnodesManage cg=new ZnodesManage();cg.connect("localhost");cg.create("zoo");//创建一个znodecg.join("zoo","duck");//创建三个子znodecg.join("zoo","goat");cg.join("zoo","cow");cg.list("zoo");//列出zoo下的znodecg.close();//关闭连接}}