我最近开始使用Python for Zookeeper。我正在为Zookeeper使用kazoo库。
我有一个使用Zookeeper的kazoo的非常简单的用例。我有一个根节点,它是- /root。现在我需要监视根节点/root,如果添加到根节点/root的新节点是/root/testing,那么我将只监视/root/testing节点。我不想监视除testing节点之外的任何其他节点。然后,如果有任何新的子节点被添加到/root/testing节点,那么我也会监视它们。
假设下面的孩子加起来-
`/root/testing/test1`然后我也会关注test1节点。
在Zookeeper中使用Kazoo可以做到这一点吗?我只能在一个Zookeeper节点(/root)上进行监视,代码如下:
#!/usr/bin/python
import time
from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
########################################
@zk.ChildrenWatch("/root/testing")
def watch_children(children):
print(children)
########################################
while True:
time.sleep(5)有没有人能帮我在子节点上做多个监视呢?
发布于 2013-11-26 05:52:08
试试这样的东西。
import time
from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
children = zk.get_children("/root/",)
if "/testing" in children:
children_testing = zk.get_children("/root/testing/")
if children_testing != []:
@zk.ChildrenWatch("/root/testing")
def watch_children(children):
print(children)
else:
@zk.ChildrenWatch("/root/")
def watch_children(children):
print(children)
while True:
time.sleep(5)发布于 2013-11-24 06:27:17
如果你试图监视多个节点,而不是一个节点,你可以使用多个线程(基本上它在不同的“线程”上同时运行不同的代码)。Python有一个用于同时执行操作的线程模块,这可能正是您想要的。下面是一个实现了线程的代码示例。
import threading
def watch_node(node):
#implement your node watching script here
def watch_in_background(node):
watcher = threading.Thread(target=watch_node,args=(node)) #initializes a thread that can run the watch_node function in the background, passing the node argument to it
watcher.start() #tells the thread to start running
return watcher #returns the thread object just in case you want to use it for something
watch_in_background(<node>) #so this code will now watch the node in the background, allowing you to do other things, like watch multiple nodeshttps://stackoverflow.com/questions/20079018
复制相似问题