实验环境:
os-platform: windows7 x64
jdk: 1.7
参考文档:
http://www.ibm.com/developerworks/cn/opensource/os-cn-zookeeper/ http://zookeeper.apache.org/doc/r3.4.6/ http://blog.csdn.net/rengq126/article/details/7393227
1.下载zookeeper,这里选用stable版本的3.4.6
下载地址:http://apache.fayea.com/zookeeper/zookeeper-3.4.6/
2.配置安装zookeeper
下载完成后,将zookeeper-3.4.6.tar.gz解压到指定目录(如,D:/zookeeper-3.4.6)。 重命名conf/zoo_sample.cfg为zoo.cfg,其中关键配置请至少保留以下项: tickTime=2000 dataDir=D:/zookeeper-3.4.6/data clientPort=2181 配置项分别为: 心跳频率,每2000ms发送一次心跳包 数据路径,可用于数据落地,确保zookeeper宕机后数据不丢失(一般用来保障那些永久性节点) 服务端口,即客户端的连接端口,zookeeper用来监听客户端的请求
3.启动和关闭,以及客户端的连接
启动方式: bin/zkServer.cmd 或 bin/zkServer.sh start 关闭方式: 遗憾的是windows只能手动Ctrl+C关掉server,而linux则可以通过bin/zkServer.sh stop完成关闭操作 客户端连接: bin/zkCli.cmd 或者 bin/zkCli.cmd -server 127.0.0.1:2181
4.zookeeper api using demo(可用来了解watcher和zk的基础操作)
package org.kongdl.zookeeper.demo; import java.io.*; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class ZookeeperDemo { private static final int SESSION_TIMEOUT = 3000; public static void main(String[] args) { ZookeeperDemo demo = new ZookeeperDemo(); try { demo.zkOperations(); } catch(Exception e) { e.printStackTrace(); } } private void zkOperations() throws IOException, InterruptedException, KeeperException{ ZooKeeper zk = createZookeeperInstance(); System.out.println(" 1. 创建 ZooKeeper 节点 (znode : zoo2, " + "数据: myData2 ," + "权限: OPEN_ACL_UNSAFE ," + "节点类型: Persistent"); zk.create("/zoo2", "mydata".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println(" 2. 查看是否创建成功: "); System.out.println(new String(zk.getData("/zoo2", true, null))); System.out.println(" 3. 修改节点数据 "); zk.setData("/zoo2", "lichmama".getBytes(), -1); System.out.println(" 4. 查看是否修改成功: "); System.out.println(new String(zk.getData("/zoo2", true, null))); System.out.println(" 5. 删除节点 "); zk.delete("/zoo2", -1); System.out.println(" 6. 查看节点是否被删除: "); System.out.println(" 节点状态: [" + zk.exists("/zoo2", true) + "]"); System.out.println(" 7. 关闭client连接"); zk.close(); } private ZooKeeper createZookeeperInstance() throws IOException { return new ZooKeeper("localhost:2181", ZookeeperDemo.SESSION_TIMEOUT, new Watcher() { public void process(org.apache.zookeeper.WatchedEvent event) { System.out.println(event.toString()); } }); } }