上一篇已经讲解了如何安装zookeeper的python客户端,接下来是我在网上搜到的例子,举例应用环境是:

1.当有两个或者多个服务运行,并且同意时间只有一个服务接受请求(工作),其他服务待命。

2.当接受请求(工作)的服务异常挂掉时,会从剩下的待命服务中选举出一个服务来接受请求(工作)。

下面直接上例子,有两个文件组成1.zkclient.py   2.zktest.py

  1. # coding: utf-8
  2. # modfied from https://github.com/phunt/zk-smoketest/blob/master/zkclient.py
  3. # zkclient.py
  4.  
  5. import zookeeper, time, threading
  6. from collections import namedtuple
  7.  
  8. DEFAULT_TIMEOUT = 30000
  9. VERBOSE = True
  10.  
  11. ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
  12.  
  13. # Mapping of connection state values to human strings.
  14. STATE_NAME_MAPPING = {
  15. zookeeper.ASSOCIATING_STATE: "associating",
  16. zookeeper.AUTH_FAILED_STATE: "auth-failed",
  17. zookeeper.CONNECTED_STATE: "connected",
  18. zookeeper.CONNECTING_STATE: "connecting",
  19. zookeeper.EXPIRED_SESSION_STATE: "expired",
  20. }
  21.  
  22. # Mapping of event type to human string.
  23. TYPE_NAME_MAPPING = {
  24. zookeeper.NOTWATCHING_EVENT: "not-watching",
  25. zookeeper.SESSION_EVENT: "session",
  26. zookeeper.CREATED_EVENT: "created",
  27. zookeeper.DELETED_EVENT: "deleted",
  28. zookeeper.CHANGED_EVENT: "changed",
  29. zookeeper.CHILD_EVENT: "child",
  30. }
  31.  
  32. class ZKClientError(Exception):
  33. def __init__(self, value):
  34. self.value = value
  35. def __str__(self):
  36. return repr(self.value)
  37.  
  38. class ClientEvent(namedtuple("ClientEvent", 'type, connection_state, path')):
  39. """
  40. A client event is returned when a watch deferred fires. It denotes
  41. some event on the zookeeper client that the watch was requested on.
  42. """
  43.  
  44. @property
  45. def type_name(self):
  46. return TYPE_NAME_MAPPING[self.type]
  47.  
  48. @property
  49. def state_name(self):
  50. return STATE_NAME_MAPPING[self.connection_state]
  51.  
  52. def __repr__(self):
  53. return "<ClientEvent %s at %r state: %s>" % (
  54. self.type_name, self.path, self.state_name)
  55.  
  56. def watchmethod(func):
  57. def decorated(handle, atype, state, path):
  58. event = ClientEvent(atype, state, path)
  59. return func(event)
  60. return decorated
  61.  
  62. class ZKClient(object):
  63. def __init__(self, servers, timeout=DEFAULT_TIMEOUT):
  64. self.timeout = timeout
  65. self.connected = False
  66. self.conn_cv = threading.Condition( )
  67. self.handle = -1
  68.  
  69. self.conn_cv.acquire()
  70. if VERBOSE: print("Connecting to %s" % (servers))
  71. start = time.time()
  72. self.handle = zookeeper.init(servers, self.connection_watcher, timeout)
  73. self.conn_cv.wait(timeout/1000)
  74. self.conn_cv.release()
  75.  
  76. if not self.connected:
  77. raise ZKClientError("Unable to connect to %s" % (servers))
  78.  
  79. if VERBOSE:
  80. print("Connected in %d ms, handle is %d"
  81. % (int((time.time() - start) * 1000), self.handle))
  82.  
  83. def connection_watcher(self, h, type, state, path):
  84. self.handle = h
  85. self.conn_cv.acquire()
  86. self.connected = True
  87. self.conn_cv.notifyAll()
  88. self.conn_cv.release()
  89.  
  90. def close(self):
  91. return zookeeper.close(self.handle)
  92.  
  93. def create(self, path, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):
  94. start = time.time()
  95. result = zookeeper.create(self.handle, path, data, acl, flags)
  96. if VERBOSE:
  97. print("Node %s created in %d ms"
  98. % (path, int((time.time() - start) * 1000)))
  99. return result
  100.  
  101. def delete(self, path, version=-1):
  102. start = time.time()
  103. result = zookeeper.delete(self.handle, path, version)
  104. if VERBOSE:
  105. print("Node %s deleted in %d ms"
  106. % (path, int((time.time() - start) * 1000)))
  107. return result
  108.  
  109. def get(self, path, watcher=None):
  110. return zookeeper.get(self.handle, path, watcher)
  111.  
  112. def exists(self, path, watcher=None):
  113. return zookeeper.exists(self.handle, path, watcher)
  114.  
  115. def set(self, path, data="", version=-1):
  116. return zookeeper.set(self.handle, path, data, version)
  117.  
  118. def set2(self, path, data="", version=-1):
  119. return zookeeper.set2(self.handle, path, data, version)
  120.  
  121. def get_children(self, path, watcher=None):
  122. return zookeeper.get_children(self.handle, path, watcher)
  123.  
  124. def async(self, path = "/"):
  125. return zookeeper.async(self.handle, path)
  126.  
  127. def acreate(self, path, callback, data="", flags=0, acl=[ZOO_OPEN_ACL_UNSAFE]):
  128. result = zookeeper.acreate(self.handle, path, data, acl, flags, callback)
  129. return result
  130.  
  131. def adelete(self, path, callback, version=-1):
  132. return zookeeper.adelete(self.handle, path, version, callback)
  133.  
  134. def aget(self, path, callback, watcher=None):
  135. return zookeeper.aget(self.handle, path, watcher, callback)
  136.  
  137. def aexists(self, path, callback, watcher=None):
  138. return zookeeper.aexists(self.handle, path, watcher, callback)
  139.  
  140. def aset(self, path, callback, data="", version=-1):
  141. return zookeeper.aset(self.handle, path, data, version, callback)
  142.  
  143. watch_count = 0
  144.  
  145. """Callable watcher that counts the number of notifications"""
  146. class CountingWatcher(object):
  147. def __init__(self):
  148. self.count = 0
  149. global watch_count
  150. self.id = watch_count
  151. watch_count += 1
  152.  
  153. def waitForExpected(self, count, maxwait):
  154. """Wait up to maxwait for the specified count,
  155. return the count whether or not maxwait reached.
  156.  
  157. Arguments:
  158. - `count`: expected count
  159. - `maxwait`: max milliseconds to wait
  160. """
  161. waited = 0
  162. while (waited < maxwait):
  163. if self.count >= count:
  164. return self.count
  165. time.sleep(1.0);
  166. waited += 1000
  167. return self.count
  168.  
  169. def __call__(self, handle, typ, state, path):
  170. self.count += 1
  171. if VERBOSE:
  172. print("handle %d got watch for %s in watcher %d, count %d" %
  173. (handle, path, self.id, self.count))
  174.  
  175. """Callable watcher that counts the number of notifications
  176. and verifies that the paths are sequential"""
  177. class SequentialCountingWatcher(CountingWatcher):
  178. def __init__(self, child_path):
  179. CountingWatcher.__init__(self)
  180. self.child_path = child_path
  181.  
  182. def __call__(self, handle, typ, state, path):
  183. if not self.child_path(self.count) == path:
  184. raise ZKClientError("handle %d invalid path order %s" % (handle, path))
  185. CountingWatcher.__call__(self, handle, typ, state, path)
  186.  
  187. class Callback(object):
  188. def __init__(self):
  189. self.cv = threading.Condition()
  190. self.callback_flag = False
  191. self.rc = -1
  192.  
  193. def callback(self, handle, rc, handler):
  194. self.cv.acquire()
  195. self.callback_flag = True
  196. self.handle = handle
  197. self.rc = rc
  198. handler()
  199. self.cv.notify()
  200. self.cv.release()
  201.  
  202. def waitForSuccess(self):
  203. while not self.callback_flag:
  204. self.cv.wait()
  205. self.cv.release()
  206.  
  207. if not self.callback_flag == True:
  208. raise ZKClientError("asynchronous operation timed out on handle %d" %
  209. (self.handle))
  210. if not self.rc == zookeeper.OK:
  211. raise ZKClientError(
  212. "asynchronous operation failed on handle %d with rc %d" %
  213. (self.handle, self.rc))
  214.  
  215. class GetCallback(Callback):
  216. def __init__(self):
  217. Callback.__init__(self)
  218.  
  219. def __call__(self, handle, rc, value, stat):
  220. def handler():
  221. self.value = value
  222. self.stat = stat
  223. self.callback(handle, rc, handler)
  224.  
  225. class SetCallback(Callback):
  226. def __init__(self):
  227. Callback.__init__(self)
  228.  
  229. def __call__(self, handle, rc, stat):
  230. def handler():
  231. self.stat = stat
  232. self.callback(handle, rc, handler)
  233.  
  234. class ExistsCallback(SetCallback):
  235. pass
  236.  
  237. class CreateCallback(Callback):
  238. def __init__(self):
  239. Callback.__init__(self)
  240.  
  241. def __call__(self, handle, rc, path):
  242. def handler():
  243. self.path = path
  244. self.callback(handle, rc, handler)
  245.  
  246. class DeleteCallback(Callback):
  247. def __init__(self):
  248. Callback.__init__(self)
  249.  
  250. def __call__(self, handle, rc):
  251. def handler():
  252. pass
  253. self.callback(handle, rc, handler)

上面的文件是别人封装好的zookeeper接口,下面是测试代码,需要依赖上面的包:

  1. # coding: utf-8
  2. # zktest.py
  3.  
  4. import logging
  5. from os.path import basename, join
  6.  
  7. from zkclient import ZKClient, zookeeper, watchmethod
  8.  
  9. logging.basicConfig(
  10. level = logging.DEBUG,
  11. format = "[%(asctime)s] %(levelname)-8s %(message)s"
  12. )
  13.  
  14. log = logging
  15.  
  16. class GJZookeeper(object):
  17.  
  18. ZK_HOST = "localhost:2181"
  19. ROOT = "/app"
  20. WORKERS_PATH = join(ROOT, "workers")
  21. MASTERS_NUM = 1
  22. TIMEOUT = 10000
  23.  
  24. def __init__(self, verbose = True):
  25. self.VERBOSE = verbose
  26. self.masters = []
  27. self.is_master = False
  28. self.path = None
  29.  
  30. self.zk = ZKClient(self.ZK_HOST, timeout = self.TIMEOUT)
  31. self.say("login ok!")
  32. # init
  33. self.__init_zk()
  34. # register
  35. self.register()
  36.  
  37. def __init_zk(self):
  38. """
  39. create the zookeeper node if not exist
  40. """
  41. nodes = (self.ROOT, self.WORKERS_PATH)
  42. for node in nodes:
  43. if not self.zk.exists(node):
  44. try:
  45. self.zk.create(node, "")
  46. except:
  47. pass
  48.  
  49. @property
  50. def is_slave(self):
  51. return not self.is_master
  52.  
  53. def register(self):
  54. """
  55. register a node for this worker
  56. """
  57. self.path = self.zk.create(self.WORKERS_PATH + "/worker", "1", flags=zookeeper.EPHEMERAL | zookeeper.SEQUENCE)
  58. self.path = basename(self.path)
  59. self.say("register ok! I'm %s" % self.path)
  60. # check who is the master
  61. self.get_master()
  62.  
  63. def get_master(self):
  64. """
  65. get children, and check who is the smallest child
  66. """
  67. @watchmethod
  68. def watcher(event):
  69. self.say("child changed, try to get master again.")
  70. self.get_master()
  71.  
  72. children = self.zk.get_children(self.WORKERS_PATH, watcher)
  73. children.sort()
  74. self.say("%s's children: %s" % (self.WORKERS_PATH, children))
  75.  
  76. # check if I'm master
  77. self.masters = children[:self.MASTERS_NUM]
  78. if self.path in self.masters:
  79. self.is_master = True
  80. self.say("I've become master!")
  81. else:
  82. self.say("%s is masters, I'm slave" % self.masters)
  83.  
  84. def say(self, msg):
  85. """
  86. print messages to screen
  87. """
  88. if self.VERBOSE:
  89. if self.path:
  90. if self.is_master:
  91. log.info("[ %s(%s) ] %s" % (self.path, "master" , msg))
  92. else:
  93. log.info("[ %s(%s) ] %s" % (self.path, "slave", msg))
  94. else:
  95. log.info(msg)
  96.  
  97. def main():
  98. gj_zookeeper = GJZookeeper()
  99.  
  100. if __name__ == "__main__":
  101. main()
  102. import time
  103. time.sleep(1000)

下面在两台机器(也可以在同一台)上运行上面的脚本可以看到如下信息:

  1. [2013-07-03 14:26:12,192] INFO login ok!
  2. Node /app/workers/worker created in 1 ms
  3. [2013-07-03 14:26:12,195] INFO [ worker0000000016(slave) ] register ok! I'm worker0000000016
  4. [2013-07-03 14:26:12,196] INFO [ worker0000000016(slave) ] /app/workers's children: ['worker0000000016']
  5. [2013-07-03 14:26:12,196] INFO [ worker0000000016(master) ] I've become master!

  1. [2013-07-03 14:26:58,277] INFO login ok!
  2. Node /app/workers/worker created in 2 ms
  3. [2013-07-03 14:26:58,281] INFO [ worker0000000017(slave) ] register ok! I'm worker0000000017
  4. [2013-07-03 14:26:58,282] INFO [ worker0000000017(slave) ] /app/workers's children: ['worker0000000016', 'worker0000000017']
  5. [2013-07-03 14:26:58,282] INFO [ worker0000000017(slave) ] ['worker0000000016'] is masters, I'm slave

先然第一台机器做了master。

下面我们关掉第一个进程,第二台在timeout(10s)时间后,会出现如下信息:

  1. [2013-07-03 14:28:02,204] INFO [ worker0000000017(slave) ] child changed, try to get master again.
  2. [2013-07-03 14:28:02,205] INFO [ worker0000000017(slave) ] /app/workers's children: ['worker0000000017']
  3. [2013-07-03 14:28:02,206] INFO [ worker0000000017(master) ] I've become master!

显然,第二台机器上的程序变成了master,这就是我们想要实现的功能。

当然开启多个进程也是可以的,并且可以在程序中选择master的数量,同时本人建议timeout时间可以取小一点,我们先上环境用的是2s。

之后会更新更多zookeeper的其他应用环境的例子。

zookeeper集群的python代码测试的更多相关文章

  1. Centos6下zookeeper集群部署记录

    ZooKeeper是一个开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等. Zookeeper设计目的 最终一致性:client不论 ...

  2. k8s 上使用 StatefulSet 部署 zookeeper 集群

    目录 StatefulSet 部署 zookeeper 集群 创建pv StatefulSet 测试 StatefulSet 部署 zookeeper 集群 参考 k8s官网zookeeper集群的部 ...

  3. zookeeper与Kafka集群搭建及python代码测试

    Kafka初识 1.Kafka使用背景 在我们大量使用分布式数据库.分布式计算集群的时候,是否会遇到这样的一些问题: 我们想分析下用户行为(pageviews),以便我们设计出更好的广告位 我想对用户 ...

  4. kafka集群和zookeeper集群的部署,kafka的java代码示例

    来自:http://doc.okbase.net/QING____/archive/19447.html 也可参考: http://blog.csdn.net/21aspnet/article/det ...

  5. 消息中间件kafka+zookeeper集群部署、测试与应用

    业务系统中,通常会遇到这些场景:A系统向B系统主动推送一个处理请求:A系统向B系统发送一个业务处理请求,因为某些原因(断电.宕机..),B业务系统挂机了,A系统发起的请求处理失败:前端应用并发量过大, ...

  6. Zookeeper集群搭建以及python操作zk

    一.Zookeeper原理简介 ZooKeeper是一个开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等. Zookeeper设计目 ...

  7. 原创:centos7.1下 ZooKeeper 集群安装配置+Python实战范例

    centos7.1下 ZooKeeper 集群安装配置+Python实战范例 下载:http://apache.fayea.com/zookeeper/zookeeper-3.4.9/zookeepe ...

  8. ZooKeeper集群的安装、配置、高可用测试

    Dubbo注册中心集群Zookeeper-3.4.6 Dubbo建议使用Zookeeper作为服务的注册中心. Zookeeper集群中只要有过半的节点是正常的情况下,那么整个集群对外就是可用的.正是 ...

  9. Dubbo入门到精通学习笔记(十三):ZooKeeper集群的安装、配置、高可用测试、升级、迁移

    文章目录 ZooKeeper集群的安装.配置.高可用测试 ZooKeeper 与 Dubbo 服务集群架构图 1. 修改操作系统的/etc/hosts 文件,添加 IP 与主机名映射: 2. 下载或上 ...

随机推荐

  1. JAVA编程心得-JAVA实现CRC-CCITT(XMODEM)算法

    CRC即循环冗余校验码(Cyclic Redundancy Check):是数据通信领域中最常用的一种差错校验码,其特征是信息字段和校验字段的长度可以任意选定. 1 byte checksum CRC ...

  2. c++中虚函数和纯虚函数定义

    只有用virtual声明类的成员函数,使之成为虚函数,不能将类外的普通函数声明为虚函数.因为虚函数的作用是允许在派生类中对基类的虚函数重新定义.所以虚函数只能用于类的继承层次结构中. 一个成员函数被声 ...

  3. C++的for循环细节,必看!

    C++中.For(A;B;C)   C语句是在每次循环后才运行. 如: y=10; for( i=0;i<10;y=++i) {    cout<<y<<endl; } ...

  4. ThinkPHP页面跳转、Ajax技巧详细介绍(十八)

    原文:ThinkPHP页面跳转.Ajax技巧详细介绍(十八) ThinkPHP页面跳转.Ajax技巧详细介绍 一.页面跳转 $this->success('查询成功',U('User/test' ...

  5. shodan

    https://www.shodan.io/ from:http://www.exploit-db.com/wp-content/themes/exploit/docs/33859.pdf 0x00 ...

  6. groovy : 正則表達式

    groovy 正則表達式 企图模仿Perl 的语法,结果是我试用后.发现没法提取匹配的字符串. 还是直接引用 java.util.regex  负责对字符序列进行正則表達式匹配 先转载水木清华上的样例 ...

  7. C++学习笔记10-面向对象

    1.  面向对象的程序设计是基于三个基本概念:数据抽象.继承和动态绑定. 在C++ 在,凭借一流的数据抽象,随着一类从一个类派生还继承:派生类的成员继承基类.决定是使用基类中定义的函数还是派生类中定义 ...

  8. Linux Shell 函数返回值

    Shell函数返回值,常用的两种方式:return,echo 1) return 语句 shell函数的返回值,可以和其他语言的返回值一样,通过return语句返回. 示例: #!/bin/sh fu ...

  9. OCA读书笔记(15) - 执行数据库备份

    物理备份 -- 数据文件,控制文件,日志文件,参数文件 数据库备份 冷备 -- 归档和非归档均可以 什么时候必须用冷备?1. 数据库的模式为非归档的2. 用于现场保护 冷备的过程:1. 首先查看备份文 ...

  10. csdn肿么了,这两天写的博文都是待审核

    昨天早上8点写了一篇博文,然后点击发表,结果系统显示"待审核".于是仅仅好qq联系csdn的客服,等到9点时候,csdn的客服上线了,然后回复说是链接达到5个以上须要审核,于是回到 ...