Python:kazoo模块与Zookeeper交互

github: https://github.com/python-zk/kazoo

文档: https://kazoo.readthedocs.io/en/latest/

安装

$ pip install kazoo

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()

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)

(2)从Zookeeper客户端修改数据

$ zkCli.sh

> create /mydata data0
Created /mydata

> set /mydata data1
> set /mydata data2

(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


参考:

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

上一篇:Python:ImportError: No module named


下一篇:robots.txt文件示例