- 安装jdk
- 安装Zookeeper. 在https://archive.apache.org/dist/zookeeper/下载对应版本(测试使用的是zookeeper-3.4.6版本)
- 解压zookeeper-3.4.6至F:\qsf\zookeeper\zookeeper-3.4.6
- 在F:\qsf\zookeeper\ 新建data及log目录
ZooKeeper的安装模式分为三种,分别为:单机模式(stand-alone)、集群模式和集群伪分布模式。ZooKeeper 单机模式的安装相对比较简单,如果第一次接触ZooKeeper的话,建议安装ZooKeeper单机模式或者集群伪分布模式。
安装单击模式。 至F:\qsf\zookeeper\zookeeper-3.4.6\conf 复制 zoo_sample.cfg 并粘贴到当前目录下,命名zoo.cfg.
编辑zoo.cfg.修改如下配置
# The number of milliseconds of each tick tickTime=2000 # The number of ticks that the initial # synchronization phase can take initLimit=10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit=5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir=F:\\qsf\\zookeeper\\data dataLogDir=F:\\qsf\\zookeeper\\data # the port at which the clients will connect clientPort=2181 # the maximum number of client connections. # increase this if you need to handle more clients #maxClientCnxns=60 # # Be sure to read the maintenance section of the # administrator guide before turning on autopurge. # # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance # # The number of snapshots to retain in dataDir #autopurge.snapRetainCount=3 # Purge task interval in hours # Set to "0" to disable auto purge feature #autopurge.purgeInterval=1dataDir=F:\qsf\zookeeper\data dataLogDir=F:\qsf\zookeeper\data
- cmd命令下进入F:\qsf\zookeeper\zookeeper-3.4.6\\bin目录下运行zkserver.cmd.如下图所示:
- 运行zkcli.cmd.如下图所示:
- 之后在搭建集群模式和集群伪分布模式
package com.demo;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class ZooKeeperTest {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 30000, new TestWatcher());
String node = "/node";
Stat stat = zk.exists(node, false);
if(null==stat) {
//创建节点
String createResult = zk.create(node, "test".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
System.out.println(createResult);
}
byte[] data = zk.getData(node, false, stat);
System.out.println(new String(data));
zk.close();
}
}
class TestWatcher implements Watcher{
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
System.out.println("*****************************");
System.out.println("path: " + event.getPath());
System.out.println("type: " + event.getType());
System.out.println("state: " + event.getState());
System.out.println("*****************************");
}
}