zookeeper python接口实例详解

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

zkpython安装

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

cd /usr/local/zookeeper/src/c
./configure
make
make install

wget --no-check-certificate http://pypi.python.org/packages/source/z/zkpython/zkpython-0.4.tar.gz
tar -zxvf zkpython-0.4.tar.gz
cd zkpython-0.4
sudo python setup.py install

zkpython应用

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

#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-

import zookeeper, time, threading
from collections import namedtuple

DEFAULT_TIMEOUT = 30000
VERBOSE = True

ZOO_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 decorated

class 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 notifications
and 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):
  pass

class 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接口实例详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

(0)

相关推荐

  • zookeeper概述图文详解

    1.1 概述 分布式系统:分布式系统指由很多台计算机组成的一个整体!这个整体一致对外,并且处理同一请求!系统对内透明,对外不透明!内部的每台计算机,都可以相互通信,例如使用RPC/REST或者是WebService!客户端向一个分布式系统发送的一次请求到接受到响应,有可能会经历多台计算机! Zookeeper是一个开源的分布式的,为分布式应用提供协调服务的Apache项目,多用作为集群提供服务的中间件! Zookeeper从设计模式角度来理解:是一个基于观察者模式设计的分布式服务管理框架,它负责

  • Springboot 整合 Dubbo/ZooKeeper 实现 SOA 案例解析

    一.为啥整合 Dubbo 实现 SOA Dubbo 不单单只是高性能的 RPC 调用框架,更是 SOA 服务治理的一种方案. 核心: 远程通信,向本地调用一样调用远程方法. 集群容错 服务自动发现和注册,可平滑添加或者删除服务提供者. 我们常常使用 Springboot 暴露 HTTP 服务,并走 JSON 模式.但慢慢量大了,一种 SOA 的治理方案.这样可以暴露出 Dubbo 服务接口,提供给 Dubbo 消费者进行 RPC 调用.下面我们详解下如何集成 Dubbo. 二.运行 spring

  • 使用dubbo+zookeeper+spring boot构建服务的方法详解

    前言 互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,Dubbo是一个分布式服务框架,在这种情况下诞生的.现在核心业务抽取出来,作为独立的服务,使前端应用能更快速和稳定的响应. Dubbo是什么 Dubbo是Alibaba开源的分布式服务框架,它最大的特点是按照分层的方式来架构,使用这种方式可以使各个层之间解耦合(或者最大限度地松耦合).从服务模型的角度来看,Dubbo采用的是一种非常简单的模型,要么是提供方提供服务,要么是消费方消费服

  • Zookeeper接口kazoo实例解析

    本文主要研究的是Zookeeper接口kazoo的相关内容,具体介绍如下. zookeeper的开发接口以前主要以java和c为主,随着python项目越来越多的使用zookeeper作为分布式集群实现,python的zookeeper接口也出现了很多,现在主流的纯python的zookeeper接口是kazoo.因此如何使用kazoo开发基于python的分布式程序是必须掌握的. 1.安装kazoo yum install python-pip pip install kazoo 安装过程中会

  • SpringCloud用Zookeeper搭建配置中心的方法

    本文介绍了SpringCloud +Zookeeper完成配置中心,分享给大家,具有如下: 使用场景 项目配置更改不需要打包,重启 提供配置文件的可视化界面 和springcloud快速整合 为什么使用zookeeper Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问题,它能提供基于类似于文件系统的目录节点树方式的数据存储, Zookeeper 作用主要是用来维护和监控存储的数据的状态变化,通过监控这些数据状态的变化,从而达到基于数据的集群管理. 怎么使

  • zookeeper监听器原理的详解

    1)监听原理详解: 1)首先要有一个main()线程 2)在main线程中创建Zookeeper客户端,这时就会创建两个线程,一个负责网络连接通信(connet),一个负责监听(listener). 3)通过connect线程将注册的监听事件发送给Zookeeper. 4)在Zookeeper的注册监听器列表中将注册的监听事件添加到列表中. 5)Zookeeper监听到有数据或路径变化,就会将这个消息发送给listener线程. 6)listener线程内部调用了process()方法. 2)常

  • linux上安装zookeeper 启动和关闭的教程

    1.zookeeper运行需要java环境所以必须先装JDK 2.下载,解压 #wget http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.12/zookeeper-3.4.12.tar.gz #tar -zxvf zookeeper-3.4.12.tar.gz 3.文件自己选择安装目录,接着进入conf,复制zoo_sample.cfg改名为zoo.cfg # cp  zoo_sample.cfg zoo.cfg 4.编辑zoo

  • linux系统安装zookeeper 服务的方法

    1.创建 /usr/local/services/zookeeper 文件夹: mkdir -p /usr/local/services/zookeeper 2.进入到 /usr/local/services/zookeeper 目录中: cd /usr/local/services/zookeeper 3.下载 zookeeper-3.4.9.tar.gz: wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper

  • 从dubbo zookeeper注册地址提取出zookeeper地址的方法

    用途 项目中使用了 dubbo,注册中心使用的 zookeeper,使用 zookeeper 实现了一个简单的分布式锁(依赖 curator),因为配置文件存在 dubbo.registry 配置,为了直接使用这个地址来创建分布式锁,写了一个简单的方法来提取 zookeeper 地址. 效果 dubbo.registry 有多种配置方式,支持所有情况,下面是常见的例子和提取结果: zookeeper://localhost:2181 zookeeper://localhost:2181?clie

  • zookeeper节点类型详解

    1)Znode有两种类型: 短暂(ephemeral):客户端和服务器端断开连接后,创建的节点自己删除 持久(persistent):客户端和服务器端断开连接后,创建的节点不删除 2)Znode有四种形式的目录节点(默认是persistent ) (1)持久化目录节点(PERSISTENT) 客户端与zookeeper断开连接后,该节点依旧存在 (2)持久化顺序编号目录节点(PERSISTENT_SEQUENTIAL) 客户端与zookeeper断开连接后,该节点依旧存在,只是Zookeeper

随机推荐