Pythonkazoo模块与Zookeeper交互

网友投稿 585 2022-05-30

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

Python:kazoo模块与Zookeeper交互

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

参考:

python kazoo 监视zookeeper节点数据发生变化

Python ZooKeeper

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python:使用PyJWT实现JSON Web Tokens加密解密
下一篇:Python爬虫:使用pyppeteer爬取动态加载的网站
相关文章