export ZOOKEEPER_HOME=/usr/local/zookeeper-3.4.6 export ZOO_LOG_DIR=$ZOOKEEPER_HOME export PATH=$ZOOKEEPER_HOME/bin:$PATH
cd /usr/local/zookeeper-3.4.6/conf cp zoo_sample.cfg zoo.cfg vim zoo.cfg ------------------------- tickTime=2000 initLimit=10 syncLimit=5 dataDir=/usr/local/zookeeper-3.4.6/data dataLogDir=/usr/local/zookeeper-3.4.6/log clientPort=2181 server.1=master:2888:3888 server.2=slave1:2888:3888 server.3=slave2:2888:3888 --------------------------
mkdir /usr/local/zookeeper-3.4.6/data mkdir /usr/local/zookeeper-3.4.6/log echo 1 > /usr/local/zookeeper-3.4.6/data/myid # for master echo 2 > /usr/local/zookeeper-3.4.6/data/myid # for slave1 echo 3 > /usr/local/zookeeper-3.4.6/data/myid # for slave2
登陆每一台机器执行: zkServer.sh restart 查看状态:zkServer.sh status
zkCli.sh -server 127.0.0.1:2181 连接到 ZooKeeper 服务
ZooKeeper 支持某些特定的四字命令字母与其的交互。它们大多是查询命令,用来获取 ZooKeeper 服务的当前状态及相关信息。用户在客户端可以通过 telnet 或 nc 向 ZooKeeper 提交相应的命令
import org.apache.zookeeper.*; import java.io.IOException; /** * Created by fang on 15/9/12. */ public class zoo implements Watcher{ /* 创建一个与服务器的连接 */ ZooKeeper zk = null; public zoo() throws IOException { zk = new ZooKeeper("master:2181", 1000,this); } / 每当 /zk 节点有变化时自动调用process函数 */ public void process(WatchedEvent event) { System.out.println("已经触发了" + event.getType() + "事件!" + event.getPath()); try { /* 由于监听只生效一次,所以每次触发事件之后要再次监听/zk,第二个参数true就是设置监听*/ System.out.println(new String(zk.getData("/zk", true, null))); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) throws IOException, KeeperException, InterruptedException { zoo zk = new zoo(); while(true){ /* 不让程序退出 */ Thread.sleep(100000); } /* zk.close(); */ } }
<dependencies> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies>