国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Zookeeper接口kazoo實例解析

2020-01-04 16:03:07
字體:
來源:轉載
供稿:網友

本文主要研究的是Zookeeper接口kazoo的相關內容,具體介紹如下。

zookeeper的開發接口以前主要以java和c為主,隨著python項目越來越多的使用zookeeper作為分布式集群實現,python的zookeeper接口也出現了很多,現在主流的純python的zookeeper接口是kazoo。因此如何使用kazoo開發基于python的分布式程序是必須掌握的。

1.安裝kazoo

yum install python-pippip install kazoo

安裝過程中會出現一些python依賴包未安裝的情況,安裝即可。

2.運行kazoo基礎例子kazoo_basic.py

import timefrom kazoo.client import KazooClientfrom kazoo.client import KazooStatedef 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, timefrom kazoo.client import KazooClientfrom kazoo.client import KazooStatefrom kazoo.recipe.lock import Lockclass 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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 亳州市| 芷江| 嘉义县| 乳源| 昭通市| 昌都县| 五华县| 通城县| 无极县| 灵川县| 读书| 阿瓦提县| 芜湖市| 宁波市| 苍溪县| 北海市| 集安市| 车致| 隆子县| 柘荣县| 阿拉善盟| 锦屏县| 黄山市| 浦北县| 金沙县| 女性| 棋牌| 松溪县| 宜阳县| 咸宁市| 湘阴县| 陕西省| 峡江县| 辽阳县| 仪征市| 克山县| 华坪县| 马公市| 炎陵县| 合川市| 吴旗县|