Zookeeper接口kazoo实例解析


Posted in Python onJanuary 22, 2018

本文主要研究的是Zookeeper接口kazoo的相关内容,具体介绍如下。

zookeeper的开发接口以前主要以java和c为主,随着python项目越来越多的使用zookeeper作为分布式集群实现,python的zookeeper接口也出现了很多,现在主流的纯python的zookeeper接口是kazoo。因此如何使用kazoo开发基于python的分布式程序是必须掌握的。

1.安装kazoo

yum install python-pip
pip install kazoo

安装过程中会出现一些python依赖包未安装的情况,安装即可。

2.运行kazoo基础例子kazoo_basic.py

import time
from kazoo.client import KazooClient
from kazoo.client import KazooState
def main():
 zk=KazooClient(hosts='127.0.0.1:2182')
 zk.start()
 
 @zk.add_listener
 def my_listener(state):
 if state == KazooState.LOST:
  print("LOST")
 elif state == KazooState.SUSPENDED:
  print("SUSPENDED")
 else:
  print("Connected")
 #Creating Nodes
 # Ensure a path, create if necessary
 zk.ensure_path("/my/favorite")
 # Create a node with data
 zk.create("/my/favorite/node", b"")
 zk.create("/my/favorite/node/a", b"A")
 #Reading Data
 # Determine if a node exists
 if zk.exists("/my/favorite"):
 print("/my/favorite is existed")
 @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/node")
 def watch_node(data, stat):
 print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
 # Print the version of a node and its data
 data, stat = zk.get("/my/favorite/node")
 print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
 # List the children
 children = zk.get_children("/my/favorite/node")
 print("There are %s children with names %s" % (len(children), children))
 #Updating Data
 zk.set("/my/favorite", b"some data")
 #Deleting Nodes
 zk.delete("/my/favorite/node/a")
 #Transactions
 transaction = zk.transaction()
 transaction.check('/my/favorite/node', version=-1)
 transaction.create('/my/favorite/node/b', b"B")
 results = transaction.commit()
 print ("Transaction results is %s" % results)
 zk.delete("/my/favorite/node/b")
 zk.delete("/my", recursive=True)
 time.sleep(2)
 zk.stop()
if __name__ == "__main__":
 try:
 main()
 except Exception, ex:
 print "Ocurred Exception: %s" % str(ex)
 quit()

运行结果:

Children are now: [u'a']
Version: 0, data: 
Version: 0, data: 
There are 1 children with names [u'a']
Children are now: []
Transaction results is [True, u'/my/favorite/node/b']
Children are now: [u'b']
Children are now: []
No handlers could be found for logger "kazoo.recipe.watchers"
LOST

以上程序运行了基本kazoo接口命令,包括创建删除加watcher等操作,通过调试并对比zookeeper服务节点znode目录结构的变化,就可以理解具体的操作结果。

3.运行通过kazoo实现的分布式锁程序kazoo_lock.py

import logging, os, time
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.recipe.lock import Lock

class ZooKeeperLock():
 def __init__(self, hosts, id_str, lock_name, logger=None, timeout=1):
 self.hosts = hosts
 self.id_str = id_str
 self.zk_client = None
 self.timeout = timeout
 self.logger = logger
 self.name = lock_name
 self.lock_handle = None
 self.create_lock()
 def create_lock(self):
 try:
 self.zk_client = KazooClient(hosts=self.hosts, logger=self.logger, timeout=self.timeout)
 self.zk_client.start(timeout=self.timeout)
 except Exception, ex:
 self.init_ret = False
 self.err_str = "Create KazooClient failed! Exception: %s" % str(ex)
 logging.error(self.err_str)
 return
 try:
 lock_path = os.path.join("/", "locks", self.name)
 self.lock_handle = Lock(self.zk_client, lock_path)
 except Exception, ex:
 self.init_ret = False
 self.err_str = "Create lock failed! Exception: %s" % str(ex)
 logging.error(self.err_str)
 return
 def destroy_lock(self):
 #self.release()
 if self.zk_client != None:
 self.zk_client.stop()
 self.zk_client = None
 def acquire(self, blocking=True, timeout=None):
 if self.lock_handle == None:
 return None
 try:
 return self.lock_handle.acquire(blocking=blocking, timeout=timeout)
 except Exception, ex:
 self.err_str = "Acquire lock failed! Exception: %s" % str(ex)
 logging.error(self.err_str)
 return None
 def release(self):
 if self.lock_handle == None:
 return None
 return self.lock_handle.release()
 def __del__(self):
 self.destroy_lock()

def main():
 logger = logging.getLogger()
 logger.setLevel(logging.INFO)
 sh = logging.StreamHandler()
 formatter = logging.Formatter('%(asctime)s -%(module)s:%(filename)s-L%(lineno)d-%(levelname)s: %(message)s')
 sh.setFormatter(formatter)
 logger.addHandler(sh)
 zookeeper_hosts = "127.0.0.1:2182"
 lock_name = "test"
 lock = ZooKeeperLock(zookeeper_hosts, "myid is 1", lock_name, logger=logger)
 ret = lock.acquire()
 if not ret:
 logging.info("Can't get lock! Ret: %s", ret)
 return
 logging.info("Get lock! Do something! Sleep 10 secs!")
 for i in range(1, 11):
 time.sleep(1)
 print str(i)
 lock.release()

if __name__ == "__main__":
 try:
 main()
 except Exception, ex:
 print "Ocurred Exception: %s" % str(ex)
 quit()

将该测试文件copy到多个服务器,同时运行,就可以看到分布式锁的效果了。

总结

以上就是本文关于Zookeeper接口kazoo实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
浅谈Python爬取网页的编码处理
Nov 04 Python
Django学习笔记之Class-Based-View
Feb 15 Python
django如何连接已存在数据的数据库
Aug 14 Python
简单的Python调度器Schedule详解
Aug 30 Python
手把手教你Python yLab的绘制折线图的画法
Oct 23 Python
python 使用opencv 把视频分割成图片示例
Dec 12 Python
python 生成任意形状的凸包图代码
Apr 16 Python
基于python实现数组格式参数加密计算
Apr 21 Python
Keras load_model 导入错误的解决方式
Jun 09 Python
python 装饰器的实际作用有哪些
Sep 07 Python
jupyter使用自动补全和切换默认浏览器的方法
Nov 18 Python
python中pandas.read_csv()函数的深入讲解
Mar 29 Python
Python调用C语言的方法【基于ctypes模块】
Jan 22 #Python
python的Crypto模块实现AES加密实例代码
Jan 22 #Python
python实现求最长回文子串长度
Jan 22 #Python
Python获取本机所有网卡ip,掩码和广播地址实例代码
Jan 22 #Python
Linux CentOS7下安装python3 的方法
Jan 21 #Python
简述Python2与Python3的不同点
Jan 21 #Python
手把手教你用python抢票回家过年(代码简单)
Jan 21 #Python
You might like
收听困难?教您超简便短波广播抗干扰方法!
2021/03/01 无线电
php操作sqlserver关于时间日期读取的小小见解
2009/11/29 PHP
解析smarty 截取字符串函数 truncate的用法介绍
2013/06/20 PHP
php的webservice的wsdl的XML无法显示问题的解决方法
2014/03/11 PHP
php代码架构的八点注意事项
2016/01/25 PHP
Zend Framework分页类用法详解
2016/03/22 PHP
Yii2使用表单上传文件的实例代码
2017/08/03 PHP
js 屏蔽鼠标右键脚本附破解方法
2009/12/03 Javascript
基于jQuery的前端数据通用验证库
2011/08/08 Javascript
JavaScript中按位“异或”运算符使用介绍
2014/03/14 Javascript
jquery移动端TAB触屏切换实现效果
2020/12/22 Javascript
jquery分页插件jquery.pagination.js使用方法解析
2016/04/01 Javascript
JavaScript+Canvas实现彩色图片转换成黑白图片的方法分析
2018/07/31 Javascript
js中获取URL参数的共用方法getRequest()方法实例详解
2018/10/24 Javascript
Vue 自定义标签的src属性不能使用相对路径的解决
2019/09/17 Javascript
taro小程序添加骨架屏的实现代码
2019/11/15 Javascript
koa2 数据api中间件设计模型的实现方法
2020/07/13 Javascript
Vue项目中数据的深度监听或对象属性的监听实例
2020/07/17 Javascript
Python实现获取命令行输出结果的方法
2017/06/10 Python
python微信跳一跳系列之色块轮廓定位棋盘
2018/02/26 Python
python3爬取数据至mysql的方法
2018/06/26 Python
django创建最简单HTML页面跳转方法
2019/08/16 Python
使用django和vue进行数据交互的方法步骤
2019/11/11 Python
Python插入Elasticsearch操作方法解析
2020/01/19 Python
Python xlwt模块使用代码实例
2020/06/10 Python
python 5个实用的技巧
2020/09/27 Python
使用Python封装excel操作指南
2021/01/29 Python
HTML5-WebSocket实现聊天室示例
2016/12/15 HTML / CSS
中国排名第一的外贸销售网站:LightInTheBox.com(兰亭集势)
2016/10/28 全球购物
韩语专业本科生求职信
2013/10/01 职场文书
经销商会议欢迎词
2014/01/11 职场文书
个人党性剖析材料
2014/02/03 职场文书
纪念九一八事变演讲稿:青少年应树立远大理想
2014/09/14 职场文书
司法局群众路线教育实践活动整改措施思想汇报
2014/10/13 职场文书
应聘教师求职信范文
2015/03/20 职场文书
消防演习感想
2015/08/10 职场文书