kazoo是zookeeper的python模块,使用python编写的。使用python写运维平台的就可以用上
1、安装
安装简单,不需要其他依赖
pip install kazoo
2、使用
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
参考:http://kazoo.readthedocs.io/en/latest/basic_usage.html#creating-nodes
'''
from kazoo.client import KazooClient
# Create a client and start it
zk = KazooClient(hosts='10.14.86.178:2181')
zk.start()
# Now you can do the regular zookepper API calls
# Ensure some paths are created required by your application
# zk.ensure_path("/app/someservice")
#watchers
# @zk.ChildrenWatch('/mysql/host')
# def mysql_watcher(children):
# print('/mysql/host changed :%s'%children)
#获取指定节点的值
# print(zk.get('/mysql/host',watch=mysql_watcher2))
# print(zk.get('/mysql/port',watch=None))
# print(zk.get('/mysql/user',watch=None))
# print(zk.get('/mysql/pwd',watch=None))
'''
Reading Data
Methods:
exists()
get() 获取key对应的value值
get_children() 获取节点下的key信息
'''
# Determine if a node exists
# if zk.exists("/redis/group1"):
# # Do something
# print(zk.get_children('/redis/group1'))
# print(zk.get('/redis/group1/host'))
'''
Creating Nodes
Methods:
ensure_path() 插入节点
create() 创建节点key,value
'''
# zk.ensure_path('/mysql/test')
# zk.create('/mysql/test/node',b'node value')
'''
Updating Data
Methods:
set()
'''
# zk.set('/mysql/test/node',b'value')
# print(zk.get('/mysql/test/node'))
'''
Deleting Nodes
Methods:
delete()
'''
zk.delete('/mysql/test',recursive=True)
# In the end, stop it
zk.stop()
2.1、连接状态 zk.state
2.2、zk.connected
已连接上返回True
没有连接上返回False
2.3、zk.get(path, watch=None)
获取指定节点的值,节点不存在触发NoNodeError异常
2.4、zk.get_children(path, watch=None)
获取指定节点子节点信息
4、后台逻辑
def base(basedir, id, pid): ''' id:当前节点的id,ID的组成是 深度 + 兄弟节点序号 + 父节点ID pid: 父节点id name: 节点名称 children: 子节点个数 deep: 深度 url: 节点的路径 ''' deep = '' try: if not zk.connected: zk.start() item = {} if basedir == '/': children = ['redis', 'game', 'uc'] else: children = zk.get_children(basedir) cut = basedir.split('/') deep = len(cut) - 1 name = cut[deep] if len(children) == 0: childrenlen = 0 else: childrenlen = len(children) item = {'id': id, 'pid': pid, 'name': name, 'children': childrenlen, 'deep': deep, 'url': basedir} datas.append(item) for i in xrange(len(children)): path = os.path.join(basedir, children[i]) cut = path.split('/') n_id = str(len(cut) - 1) + str(i) + str(id) base(path, n_id, id) except Exception, e: data = str(e) return datas def get_children(req): status = 0 message = '' data = [] global datas datas = [] basedir = '/' try: data = base(basedir, '10', '0') except Exception, e: status = -1 message = str(e) zk.stop() result = stringify(status, message, data) return HttpResponse(result)
|
参考资料:
https://kazoo.readthedocs.org/en/latest/install.html
http://sapser.github.io/python/zookeeper/2014/07/24/zookeeper-kazoo/
转自:
http://zgssheng.cn/2015/04/kazoo-zookeeper-python%E6%A8%A1%E5%9D%97%E7%9A%84%E4%BD%BF%E7%94%A8/