本文主要研究的是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
新聞熱點
疑難解答