python3 连接 zookeeper

时间:2019-11-18
本文章向大家介绍python3 连接 zookeeper,主要包括python3 连接 zookeeper使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

zookeeper的增 删 改 查 watch监听。

from  kazoo.client import KazooClient
import time,os
import timeit
os.chdir(os.getcwd())
def connection():
    zk=KazooClient('localhost:2181')
    zk.start()
    #print(zk.connected)
    if zk.connected == "True":
        kk = "success"
    else:
        kk = "failed"
    print(zk.connected)
    return zk.connected
def Utime(f):
    def timechange(*args,**kwargs):
        start_time=time.time()
        f(*args,**kwargs)
        end_time=time.time()
        execution_time=(end_time-start_time)*1000
        return execution_time
    return timechange

#增
@Utime
def create(hosts,path,data):
    zk = KazooClient(hosts)
    zk.start()
    value=data.encode()
    zk.create(path,value,makepath=True)
    zk.stop()

#删
@Utime
def delete(hosts,path):
    zk1=KazooClient(hosts)
    zk1.start()
    zk1.delete(path)
    zk1.stop()

#查
@Utime
def get(hosts,path):
    zk2=KazooClient(hosts)
    zk2.start()
    zk2.get(path)
    zk2.stop()
 #   return data

#改
@Utime
def set(hosts,path,data):
    zk3=KazooClient(hosts)
    zk3.start()
    value=data.encode()
    zk3.set(path,value)
    zk3.stop()
#递归删
def delete_all(hosts,path):
    zk4=KazooClient(hosts)
    zk4.start(timeout=10)
    zk4.delete(path,recursive=True)
    zk4.stop()

#watch
def node_Watch(host,path):
    zk=KazooClient(host)
    zk.start()
    @zk.DataWatch(path)
    def my_change(data, stat):
        time.sleep(3)
        #print("Data is %s" % data)
        #print("Version is %s" % stat.version)
        #print("Event is %s" % event)
    while True:
        time.sleep(3)
        #print("OK")

  

原文地址:https://www.cnblogs.com/cyanrose/p/11882963.html