安装:pip install kazoo
1、链接
from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
zk.stop()
2、创建节点
Ensure a path, create if necessary
zk.ensure_path("/my/favorite")
Create a node with data
zk.create("/my/favorite/node", b"a value")
3、获取数据
Determine if a node exists
if zk.exists("/my/favorite"):
# Do something
Print the version of a node and its data
data, stat = zk.get("/my/favorite")
print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
List the children
children = zk.get_children("/my/favorite")
print("There are %s children with names %s" % (len(children), children))
4、更新数据
zk.set("/my/favorite", b"some data")
5、递归删除节点
zk.delete("/my/favorite/node", recursive=True)
6、监视节点变化
@zk.ChildrenWatch("/my/favorite/node")
def watch_children(children):
print("Children are now: %s" % children)
Above function called immediately, and from then on
@zk.DataWatch("/my/favorite")
def watch_node(data, stat):
print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
7、监听事件:LOST/CONNECTED/SUSPENDED
from kazoo.client import KazooState
def my_listener(state):
if state == KazooState.LOST:
# Register somewhere that the session was lost
elif state == KazooState.SUSPENDED:
# Handle being disconnected from Zookeeper
else:
# Handle being connected/reconnected to Zookeeper
zk.add_listener(my_listener)
8、kazoo支持异步
9、API DOCUMENT:https://kazoo.readthedocs.io/en/latest/api/client.html