Python connect zookeeper use the kazoo module

weixin_33912246發表於2019-01-08

doc:http://kazoo.readthedocs.org/en/latest/basic_usage.html

eg:
from kazoo.client import KazooClient

zk = KazooClient()
zk.start()
#!/bin/env python

#Zookeeper test
#Date 2013-03-11

import sys
sys.path.append('/global/exec/weizhong/lib')
import time
from kazoo.client import KazooClient

#init the client connect tb055 zookeeper server
zk = KazooClient('tb055:2181',10.0)
zk.start()

#lock =zk.Lock('/weidata')

#get the list 
children = zk.get_children('/')
print children
#exec ruok command
ruok = zk.command('ruok')
print ruok
#get the version of the zookeeper server 
version = zk.server_version()
print version
#create
if not zk.exists('/weizhong'):
	zk.create('/weizhong',b'Welcome to the servr on tb055')
print zk.exists('/weizhong1')
data,state = zk.get('/weizhong')

print data
print state


#stop the session
#zk.stop()
#watcher test
#當改變時呼叫
@zk.ChildrenWatch("/")
def watch_children(children):
    print("Children are now: %s" % children)
    time.sleep(5)
# Above function called immediately, and from then on

@zk.DataWatch("/weidata")
def watch_node(data, stat):
    print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))


def my_func(event):
    #check to see what the children are now
    print 30*'-'

# Call my_func when the children change
children = zk.get_children("/", watch=my_func)
zk.stop()

相關文章