使用python的kazoo模块连接zookeeper实现最基本的增删改查

kazoo的官方文档地址:https://kazoo.readthedocs.io/en/latest/index.html

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" 
                                                    __----~~~~~~~~~~~------___
                                   .  .   ~~//====......          __--~ ~~
                   -.            \_|//     |||\\  ~~~~~~::::... /~
               ___-==_       _-~o~  \/    |||  \\            _/~~-
        __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
    _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
  .~       .~       |   \\ -_    /  /-   /   ||      \   /
 /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
          '         ~-|      /|    |-~\~~       __--~~
                      |-~~-_/ |    |   ~\_   _-~            /\
                           /  \     \__   \/~                \__
                       _--~ _/ | .-~~____--~-/                  ~~==.
                      ((->/~   '.|||' -_|    ~~-/ ,              . _||
                                 -_     ~\      ~~---l__i__i__i--~~_/
                                 _-~-__   ~)  \--______________--~~
                               //.-~~~-~_--~- |-------~~~~~~~~
                                      //.-~~~--\
                               神兽保佑
                              代码无BUG!

"""
# zookeeper集群地址
# server.1=192.168.0.162:2888:3888
# server.2=192.168.0.162:2889:3889
# server.3=192.168.0.162:2890:3890


# pip install kazoo

from kazoo.client import KazooClient

# 连接zookeeper
zk = KazooClient(hosts="192.168.0.162:2181,192.168.0.162:2182,192.168.0.162:2183")


# 启动连接
zk.start()

# 创建
## 创建节点
# zk.ensure_path("/my/favorite")

## 节点添加数据,必须是byte
# zk.create("/my/favorite/node", b"a value")
# zk.create("/my/favorite/name1", b"111111")
# zk.create("/my/favorite/name2", b"222222")

# 获取节点数据
# data, stat = zk.get("/my/favorite/node")
# print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
# Version: 0, data: a value

# 列出节点数据
# children = zk.get_children("/my/favorite")
# print("There are %s children with names %s" % (len(children), children))
# There are 3 children with names ['node', 'name2', 'name1']

# 修改节点数据
# zk.set("/my/favorite/node", b"some data")

# 删除节点数据
zk.delete("/my/favorite/name2", recursive=True)

# 关闭连接
zk.stop()


posted @ 2019-09-19 17:16  哈喽哈喽111111  阅读(1529)  评论(0编辑  收藏  举报