Python's basic operations on zookeeper
#!/usr/bin/env python# -*- coding: utf-8 -*-import sysfrom kazoo.client import kazooclientdef main (): try: nodePath = "/zktest" host = " 172.16.48.171 " port = " 2181 " timeout = 100 zkc = kazooclient (hosts=host + ': ' + port, timeout=timeout) zkc.start () # determine if a node exists if zkc.exists (nodepath+ "/test111"): print nodePath + "/test111", "exist" else: # build node, return to new node path after success childrenpath = zkc.create (NodePath + "/test111", "test111") print "Create node:", childrenpath, "succeeded." # Create a temporary node, and the node automatically deletes it when the connection is broken zkc.create (nodepath+ "/test999", "test999", ephemeral=true) # get node data and node data, return 2 values, one is node data, One is the node stat, which is a Znodestat object, which is actually a node attribute, a total of 12 properties dataandstat = zkc.get (Nodepath) data = dataAndStat[0] print "Data:", data stat = dataandstat[1] print "The data version number is:", stat.version print "Data length is:", stat.data_length print "Number of child nodes:", stat.numChildren # Update node data, the maximum data is 1MB more than the error, after successful return ZnodeStat objects stat = zkc.set (nodepath, value= "test222") print "Data version number:", stat.version # Delete node, the following parameters are used to control whether recursive deletion, the default is false, but this will have a problem, if there are child nodes under the node then this deletion fails, you need to delete the first # all child nodes below it line if Zkc.exists (nodepath+ "/test111"): result = zkc.delete (nodepath+ "/test111 ", recursive=false) if result: print "Delete node succeeded. " print nodePath + " sub-nodes are: ", zkc.get_ Children (Nodepath) zkc.close () zkc.stop () except Exception as err: print err.messageif __name__ == "__main__": try: main () finally: sys.exit ()
Watcher Event actions
#!/usr/bin/env python# -*- coding: utf-8 -*-import sysimport timefrom kazoo.client import kazooclientfrom kazoo.client import childrenwatchfrom Kazoo.client import datawatch "" "Watcher can be set in two ways, one is passed in when the ZK client method is called, such as zk.get_children ("/ Node ", watch=fun), but this method is a one-time trigger is gone, if you want to continue to listen to an event you need to register again. Another way is through the Advanced API implementation, monitoring data or node changes, it only requires us to register once. One-time event attention is zookeeper default even in the Java client, this high-level API is zkclient in Java, and in Python is kazoo. The Advanced API is actually the encapsulation of the low-level API, which is more useful to users. "" "__metaclass__ = typeclass zkwatchertest: def __init__ (Self, host, port, timeout=10): self._nodename = ' self._host = host self._port = port self._ timeout = timeout self._zk = kazooclient (hosts=self._host + ': ' + Self._port, timeout=self._timeout) self._zk.start () self._lastNodeList = [] def Start (Self, zkpath): self._lastnodelist = self._ Zk.get_children (Zkpath) try: childrenwatch (client=self._zk, path=zkpath, func=self._ Nodechange) datawatch (CLIENT=SELF._ZK, path=zkpath, func=self._datachange) # The Dead loop here is to keep the program from exiting While true: &nBsp; time.sleep ( ) print "OK" except Exception as err: print err.message def _ Nodechange (Self, children): "" " processing sub-node changes :p aram children: This parameter does not need to be passed in, because passing this method into Chiledrenwatcher returns a list of current child nodes :return: "" " # print children # If the new node list length is greater than the last obtained node list length, it indicates an increase of If len (children) > len (self._lastnodelist): for node in children: if node not in self._lastNodeList: print "Newly Added nodes:",  STR (node) self._lastNodeList = children else: for node in self._lastNodeList: if node not in children: print "Deleted node:", str (node) self._lastnodelist = children def _datachange (Self, data, stat): "" " Processing node data changes :p aram data: :p aram stat: :return: "" print "Data Changes" print "Data:", data print "Data length:", stat.datalength print "Data version number:", stat.version print "Cversion:", stat.cversion print "Number of child nodes:", stat.numchildrendef main (): try: zkwt =zkwatchertest (host= "172.16.48.171", port= "2181") zkwt.start ("/zktest") except Exception as err: print err.messageif __name__ == "__main__": try: main () finally: Sys.exit ()
Zookeeper detailed (10): Python Connection and Operation zookeeper