【问题标题】:How to watch on descendant child nodes in Python using kazoo?如何使用 kazoo 在 Python 中观看后代子节点?
【发布时间】:2013-12-03 10:43:20
【问题描述】:

我最近开始使用Python for Zookeeper。我正在为 Zookeeper 使用 kazoo 库。

我有一个非常简单的用例,将kazoo 用于 Zookeeper。我有一个根节点 - /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)

谁能帮我在子节点上制作多个手表?

【问题讨论】:

    标签: python apache-zookeeper watch kazoo


    【解决方案1】:

    试试这样的。

    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)
    

    【讨论】:

      【解决方案2】:

      如果您尝试监视多个节点而不是一个节点,则可以使用多个线程(基本上它在不同的“线程”上同时运行不同的代码)。 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 nodes
      

      【讨论】:

      • 感谢您的帮助,但我的问题与动物园管理员的 kazoo 库特别相关,我无法理解如何将手表放在父母孩子身上,然后也放在孩子身上。
      • 使用 Kazoo 监视节点的脚本可以使用线程一次执行多次。 Kazoo 的使用不应影响线程。
      猜你喜欢
      • 2013-12-02
      • 2015-06-25
      • 2017-03-02
      • 2013-12-02
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多