Python:kazoo模块与Zookeeper交互
【摘要】 github: https://github.com/python-zk/kazoo 文档: https://kazoo.readthedocs.io/en/latest/
安装
$ pip install kazoo
1
关于Zookeeper安装配置可参考: Zookeeper单机模式和集群模式环境搭建
启动Zookeeper服务
$ zkServer.s...
github: https://github.com/python-zk/kazoo
文档: https://kazoo.readthedocs.io/en/latest/
安装
$ pip install kazoo
- 1
关于Zookeeper安装配置可参考:
Zookeeper单机模式和集群模式环境搭建
启动Zookeeper服务
$ zkServer.sh start zoo.cfg
- 1
1、CURD代码示例
>>> from kazoo.client import KazooClient
>>> zk = KazooClient(hosts='127.0.0.1:2181')
# zkCli.sh
>>> zk.start()
# ls /
>>> zk.get_children("/")
['zookeeper']
# create /mydata data
>>> zk.create("/mydata", "data".encode())
'/mydata'
# get /mydata
>>> zk.get("/mydata")
(b'data',
ZnodeStat(czxid=40, mzxid=40, ctime=1560494490063, mtime=1560494490063, version=0, cversion=0,
aversion=0, ephemeralOwner=0, dataLength=4, numChildren=0, pzxid=40))
# set /mydata data2
>>> zk.set("/mydata", "data2".encode())
ZnodeStat(czxid=40, mzxid=41, ctime=1560494490063, mtime=1560494514269, version=1, cversion=0,
aversion=0, ephemeralOwner=0, dataLength=5, numChildren=0, pzxid=40)
# delete /mydata
>>> zk.delete("/mydata")
True
#
>>> zk.exists("/mydata")
# quit
>>> zk.stop()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
2、监视Zookeeper节点数据发生变化
(1)Python代码
# -*- coding: utf-8 -*-
import time
from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
# 启动
zk.start()
@zk.DataWatch("/mydata")
def watch_children(data, stat): print("Data is %s" % data) if data: print("Version is %s" % stat.version)
while True: time.sleep(10)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
(2)从Zookeeper客户端修改数据
$ zkCli.sh
> create /mydata data0
Created /mydata
> set /mydata data1
> set /mydata data2
- 1
- 2
- 3
- 4
- 5
- 6
- 7
(3)监听到的数据变化
Data is None
Data is b'data0'
Version is 0
Data is b'data1'
Version is 1
Data is b'data2'
Version is 2
- 1
- 2
- 3
- 4
- 5
- 6
- 7
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/91975169
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)