下面列举一些,ZooKeeper的命令操作实例:
连接server
- bin/zkCli.sh -server 10.1.39.43:4180
列出指定node的子node
- [zk: 10.1.39.43:4180(CONNECTED) 9] ls /
- [hello, filesync, zookeeper, xing, server, group, log]
- [zk: 10.1.39.43:4180(CONNECTED) 10] ls /hello
- []
创建znode节点, 并指定关联数据
- create /hello world
创建节点/hello, 并将字符串"world"关联到该节点中.
获取znode的数据和状态信息
- [zk: 10.1.39.43:4180(CONNECTED) 7] get /hello
- world
- cZxid = 0x10000042c
- ctime = Fri May 17 17:57:33 CST 2013
- mZxid = 0x10000042c
- mtime = Fri May 17 17:57:33 CST 2013
- pZxid = 0x10000042c
- cversion = 0
- dataVersion = 0
- aclVersion = 0
- ephemeralOwner = 0x0
- dataLength = 5
- numChildren = 0
删除znode
- [zk: localhost:4180(CONNECTED) 13] delete /xing/item0000000001
- [zk: localhost:4180(CONNECTED) 14] delete /xing
- Node not empty: /xing
使用delete命令可以删除指定znode. 当该znode拥有子znode时, 必须先删除其所有子znode, 否则操作将失败. rmr命令可用于代替delete命令, rmr是一个递归删除命令, 如果发生指定节点拥有子节点时, rmr命令会首先删除子节点.
使用-e参数指定创建ephemeral节点.
- [zk: localhost:4180(CONNECTED) 4] create -e /xing/ei world
- Created /xing/ei
使用-s参数指定创建sequence节点.
- [zk: localhost:4180(CONNECTED) 0] create -s /xing/item world
- Created /xing/item0000000001
- [zk: localhost:4180(CONNECTED) 1] create -s /xing/item world
- Created /xing/item0000000002
- [zk: localhost:4180(CONNECTED) 2] create -s /xing/item world
- Created /xing/item0000000003
- [zk: localhost:4180(CONNECTED) 3] create -s /xing/item world
- Created /xing/item0000000004
ls命令. ls命令的第一个参数指定znode, 第二个参数如果为true, 则说明监听该znode的子节点的增减, 以及该znode本身的删除事件.
- [zk: localhost:4180(CONNECTED) 21] ls /xing true
- []
- [zk: localhost:4180(CONNECTED) 22] create /xing/item item000
- WATCHER::
- WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/xing
- Created /xing/item
get命令. get命令的第一个参数指定znode, 第二个参数如果为true, 则说明监听该znode的更新和删除事件.
- [zk: localhost:4180(CONNECTED) 39] get /xing true
- world
- cZxid = 0x100000066
- ctime = Fri May 17 22:30:01 CST 2013
- mZxid = 0x100000066
- mtime = Fri May 17 22:30:01 CST 2013
- pZxid = 0x100000066
- cversion = 0
- dataVersion = 0
- aclVersion = 0
- ephemeralOwner = 0x0
- dataLength = 5
- numChildren = 0
- [zk: localhost:4180(CONNECTED) 40] create /xing/item item000
- Created /xing/item
- [zk: localhost:4180(CONNECTED) 41] rmr /xing
- WATCHER::
- WatchedEvent state:SyncConnected type:NodeDeleted path:/xing
stat命令. stat命令用于获取znode的状态信息. 第一个参数指定znode, 如果第二个参数为true, 则监听该node的更新和删除事件.
ps:注意上面这个例子,在/xing下建立子节点的时候,/xing/item,watch并没有触发。因为getData对于子节点创建这种事件是不会触发的,详见:
http://wjy320.iteye.com/blog/2078655