文章目录
安装Zookeeper
下载
官网下载Zookeeper,会得到一个tar包,如:apache-zookeeper-3.8.4-bin.tar.gz
解压
tar -xvf apache-zookeeper-3.8.4-bin.tar.gz -C /usr/local/bin/
-x:解压
-v:显示所有过程
-f:最后一个参数,且是必须的,代表文件名
-C:解压到指定目录下
解压后的目录结构
- bin目录:存放着启动Zookeeper的脚本。
- conf目录:保存配置文件。
- lib目录:包括Java的JAR文件,这些JAR是运行Zookeeper的第三方文件。
运行Zookeeper
在Zookeeper包的根目录下,复制一份配置文件
cp conf/zoo_sample.cfg conf/zoo.cfg
修改dataDir
dataDir=/usr/local/data/zookeeper
手动创建一下对应目录
mkdir xxx
启动Server
sh zkServer.sh start
输出结果
/usr/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/local/bin/apache-zookeeper-3.8.4-bin/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
启动客户端
sh zkCli.sh
日志输出
2024-11-27 08:35:45,610 [myid:localhost:2181] - INFO [main-SendThread(localhost:2181):o.a.z.ClientCnxn$SendThread@1013] - Socket connection established, initiating session, client: /0:0:0:0:0:0:0:1:55800, server: localhost/0:0:0:0:0:0:0:1:2181
2024-11-27 08:35:45,673 [myid:localhost:2181] - INFO [main-SendThread(localhost:2181):o.a.z.ClientCnxn$SendThread@1453] - Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, session id = 0x100001d014f0000, negotiated timeout = 30000
WATCHER::
WatchedEvent state:SyncConnected type:None path:null
[zk: localhost:2181(CONNECTED) 0]
[zk: localhost:2181(CONNECTED) 0]
连接过程
- 客户端启动程序来建立一个会话
- 客户端尝试连接到 localhost / 127.0.0.1:2181
- 客户端连接成功,服务器开始初始化这个会话
- 会话初始化完成
- 服务器向客户端发送一个SyncConnected事件
基本操作
列出根下的所有znode
[zk: localhost:2181(CONNECTED) 0] ls /
[zookeeper]
[zk: localhost:2181(CONNECTED) 1]
创建一个名为/workers的znode
[zk: localhost:2181(CONNECTED) 1] create /workers ""
Created /workers
[zk: localhost:2181(CONNECTED) 2] ls /
[workers, zookeeper]
[zk: localhost:2181(CONNECTED) 3]
删除znode
[zk: localhost:2181(CONNECTED) 3] delete /workers
[zk: localhost:2181(CONNECTED) 4] ls /
[zookeeper]
[zk: localhost:2181(CONNECTED) 5]
设置数据、获取数据
[zk: localhost:2181(CONNECTED) 17] create /test
Created /test
[zk: localhost:2181(CONNECTED) 18] set /test "hello"
[zk: localhost:2181(CONNECTED) 19] get /test
hello
[zk: localhost:2181(CONNECTED) 20]
[zk: localhost:2181(CONNECTED) 20] ls /
[test, workers, zookeeper]
[zk: localhost:2181(CONNECTED) 21]