侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

zookeeper python接口实例详解

Python  /  管理员 发布于 7年前   227

本文主要讲python支持zookeeper的接口库安装和使用。zk的python接口库有zkpython,还有kazoo,下面是zkpython,是基于zk的C库的python接口。

zkpython安装

前提是zookeeper安装包已经在/usr/local/zookeeper下

cd /usr/local/zookeeper/src/c./configuremakemake installwget --no-check-certificate http://pypi.python.org/packages/source/z/zkpython/zkpython-0.4.tar.gztar -zxvf zkpython-0.4.tar.gzcd zkpython-0.4sudo python setup.py install

zkpython应用

下面是网上一个zkpython的类,用的时候只要import进去就行
vim zkclient.py

#!/usr/bin/env python2.7# -*- coding: UTF-8 -*-import zookeeper, time, threadingfrom collections import namedtupleDEFAULT_TIMEOUT = 30000VERBOSE = TrueZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}# Mapping of connection state values to human strings.STATE_NAME_MAPPING = {  zookeeper.ASSOCIATING_STATE: "associating",  zookeeper.AUTH_FAILED_STATE: "auth-failed",  zookeeper.CONNECTED_STATE: "connected",  zookeeper.CONNECTING_STATE: "connecting",  zookeeper.EXPIRED_SESSION_STATE: "expired",}# Mapping of event type to human string.TYPE_NAME_MAPPING = {  zookeeper.NOTWATCHING_EVENT: "not-watching",  zookeeper.SESSION_EVENT: "session",  zookeeper.CREATED_EVENT: "created",  zookeeper.DELETED_EVENT: "deleted",  zookeeper.CHANGED_EVENT: "changed",  zookeeper.CHILD_EVENT: "child", }class ZKClientError(Exception):  def __init__(self, value):    self.value = value  def __str__(self):    return repr(self.value)class ClientEvent(namedtuple("ClientEvent", 'type, connection_state, path')):  """  A client event is returned when a watch deferred fires. It denotes  some event on the zookeeper client that the watch was requested on.  """  @property  def type_name(self):    return TYPE_NAME_MAPPING[self.type]  @property  def state_name(self):    return STATE_NAME_MAPPING[self.connection_state]  def __repr__(self):    return "<ClientEvent %s at %r state: %s>" % (      self.type_name, self.path, self.state_name)def watchmethod(func):  def decorated(handle, atype, state, path):    event = ClientEvent(atype, state, path)    return func(event)  return decoratedclass ZKClient(object):  def __init__(self, servers, timeout=DEFAULT_TIMEOUT):    self.timeout = timeout    self.connected = False    self.conn_cv = threading.Condition( )    self.handle = -1    self.conn_cv.acquire()    if VERBOSE: print("Connecting to %s" % (servers))    start = time.time()    self.handle = zookeeper.init(servers, self.connection_watcher, timeout)    self.conn_cv.wait(timeout/1000)    self.conn_cv.release()    if not self.connected:      raise ZKClientError("Unable to connect to %s" % (servers))    if VERBOSE:      print("Connected in %d ms, handle is %d"         % (int((time.time() - start) * 1000), self.handle))  def connection_watcher(self, h, type, state, path):    self.handle = h    self.conn_cv.acquire()    self.connected = True    self.conn_cv.notifyAll()    self.conn_cv.release()  def close(self):    return zookeeper.close(self.handle)  def create(self, path, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):    start = time.time()    result = zookeeper.create(self.handle, path, data, acl, flags)    if VERBOSE:      print("Node %s created in %d ms"         % (path, int((time.time() - start) * 1000)))    return result  def delete(self, path, version=-1):    start = time.time()    result = zookeeper.delete(self.handle, path, version)    if VERBOSE:      print("Node %s deleted in %d ms"         % (path, int((time.time() - start) * 1000)))    return result  def get(self, path, watcher=None):    return zookeeper.get(self.handle, path, watcher)  def exists(self, path, watcher=None):    return zookeeper.exists(self.handle, path, watcher)  def set(self, path, data="", version=-1):    return zookeeper.set(self.handle, path, data, version)  def set2(self, path, data="", version=-1):    return zookeeper.set2(self.handle, path, data, version)  def get_children(self, path, watcher=None):    return zookeeper.get_children(self.handle, path, watcher)  def async(self, path = "/"):    return zookeeper.async(self.handle, path)  def acreate(self, path, callback, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):    result = zookeeper.acreate(self.handle, path, data, acl, flags, callback)    return result  def adelete(self, path, callback, version=-1):    return zookeeper.adelete(self.handle, path, version, callback)  def aget(self, path, callback, watcher=None):    return zookeeper.aget(self.handle, path, watcher, callback)  def aexists(self, path, callback, watcher=None):    return zookeeper.aexists(self.handle, path, watcher, callback)  def aset(self, path, callback, data="", version=-1):    return zookeeper.aset(self.handle, path, data, version, callback)watch_count = 0"""Callable watcher that counts the number of notifications"""class CountingWatcher(object):  def __init__(self):    self.count = 0    global watch_count    self.id = watch_count    watch_count += 1  def waitForExpected(self, count, maxwait):    """Wait up to maxwait for the specified count,    return the count whether or not maxwait reached.    Arguments:    - `count`: expected count    - `maxwait`: max milliseconds to wait    """    waited = 0    while (waited < maxwait):      if self.count >= count:        return self.count      time.sleep(1.0);      waited += 1000    return self.count  def __call__(self, handle, typ, state, path):    self.count += 1    if VERBOSE:      print("handle %d got watch for %s in watcher %d, count %d" %         (handle, path, self.id, self.count))"""Callable watcher that counts the number of notificationsand verifies that the paths are sequential"""class SequentialCountingWatcher(CountingWatcher):  def __init__(self, child_path):    CountingWatcher.__init__(self)    self.child_path = child_path  def __call__(self, handle, typ, state, path):    if not self.child_path(self.count) == path:      raise ZKClientError("handle %d invalid path order %s" % (handle, path))    CountingWatcher.__call__(self, handle, typ, state, path)class Callback(object):  def __init__(self):    self.cv = threading.Condition()    self.callback_flag = False    self.rc = -1  def callback(self, handle, rc, handler):    self.cv.acquire()    self.callback_flag = True    self.handle = handle    self.rc = rc    handler()    self.cv.notify()    self.cv.release()  def waitForSuccess(self):    while not self.callback_flag:      self.cv.wait()    self.cv.release()    if not self.callback_flag == True:      raise ZKClientError("asynchronous operation timed out on handle %d" %   (self.handle))    if not self.rc == zookeeper.OK:      raise ZKClientError(        "asynchronous operation failed on handle %d with rc %d" %        (self.handle, self.rc))class GetCallback(Callback):  def __init__(self):    Callback.__init__(self)  def __call__(self, handle, rc, value, stat):    def handler():      self.value = value      self.stat = stat    self.callback(handle, rc, handler)class SetCallback(Callback):  def __init__(self):    Callback.__init__(self)  def __call__(self, handle, rc, stat):    def handler():      self.stat = stat    self.callback(handle, rc, handler)class ExistsCallback(SetCallback):  passclass CreateCallback(Callback):  def __init__(self):    Callback.__init__(self)  def __call__(self, handle, rc, path):    def handler():      self.path = path    self.callback(handle, rc, handler)class DeleteCallback(Callback):  def __init__(self):    Callback.__init__(self)  def __call__(self, handle, rc):    def handler():      pass    self.callback(handle, rc, handler)

总结

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


  • 上一条:
    python使用logging模块发送邮件代码示例
    下一条:
    Python获取当前函数名称方法实例分享
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客