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备份文件的脚本
Aug 11 Python
基于Django模板中的数字自增(详解)
Sep 05 Python
Python进程间通信Queue实例解析
Jan 25 Python
python实现傅里叶级数展开的实现
Jul 21 Python
Python正则表达式实现简易计算器功能示例
May 07 Python
Python基于Opencv来快速实现人脸识别过程详解(完整版)
Jul 11 Python
pycharm修改文件的默认打开方式的步骤
Jul 29 Python
Flask项目中实现短信验证码和邮箱验证码功能
Dec 05 Python
解决Python列表字符不区分大小写的问题
Dec 19 Python
如何将Pycharm中调整字体大小的方式设置为"ctrl+鼠标滚轮上下滑"
Nov 17 Python
解决PyCharm无法使用lxml库的问题(图解)
Dec 22 Python
python lambda 表达式形式分析
Apr 03 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
全国FM电台频率大全 - 26 西藏自治区
2020/03/11 无线电
Trying to clone an uncloneable object of class Imagic的解决方法
2012/01/11 PHP
yii2分页之实现跳转到具体某页的实例代码
2016/06/02 PHP
PHP7.0连接DB操作实例分析【基于mysqli】
2019/09/26 PHP
小议Function.apply()之二------利用Apply的参数数组化来提高 JavaScript程序性能
2006/11/30 Javascript
JavaScript中__proto__与prototype的关系深入理解
2012/12/04 Javascript
js实现的map方法示例代码
2014/01/13 Javascript
jquery使用$(element).is()来判断获取的tagName
2014/08/24 Javascript
5个书写JavaScript代码的坏习惯,看看你中枪了没?
2014/11/06 Javascript
js实现的四级左侧网站分类菜单实例
2015/05/06 Javascript
jQuery实现点击某个div打开层,点击其他div关闭层实例分析(阻止冒泡)
2016/11/18 Javascript
jQuery如何跳转到另一个网页 就这么简单
2016/12/28 Javascript
jQuery Mobile漏洞会有跨站脚本攻击风险
2017/02/12 Javascript
移动端使用localResizeIMG4压缩图片
2017/04/22 Javascript
Node.js中使用mongoose操作mongodb数据库的方法
2017/09/12 Javascript
Vue-cli 使用json server在本地模拟请求数据的示例代码
2017/11/02 Javascript
react在安卓中输入框被手机键盘遮挡问题的解决方法
2018/09/03 Javascript
浅谈小程序 setData学问多
2019/02/20 Javascript
js中的this的指向问题详解
2019/08/29 Javascript
Vue学习之常用指令实例详解
2020/01/06 Javascript
js实现弹幕飞机效果
2020/08/27 Javascript
Python中文分词工具之结巴分词用法实例总结【经典案例】
2017/04/15 Python
django文档学习之applications使用详解
2018/01/29 Python
Python函数参数类型及排序原理总结
2019/12/19 Python
pytorch实现seq2seq时对loss进行mask的方式
2020/02/18 Python
使用tensorflow框架在Colab上跑通猫狗识别代码
2020/04/26 Python
Selenium结合BeautifulSoup4编写简单的python爬虫
2020/11/06 Python
css3中用animation的steps属性制作帧动画
2019/04/25 HTML / CSS
全方位了解CSS3的Regions扩展
2015/08/07 HTML / CSS
HTML5中5个简单实用的API(第二篇,含全屏、可见性、拍照、预加载、电池状态)
2014/05/07 HTML / CSS
日本无添加化妆品:HABA
2016/08/18 全球购物
教师个人发展总结
2015/02/11 职场文书
幼儿园辞职信范文
2015/02/27 职场文书
2015年保险公司工作总结
2015/04/24 职场文书
如何起草一份正确的合伙创业协议书?
2019/07/04 职场文书
详细了解MVC+proxy
2021/07/09 Java/Android