0

我试图了解如何做到这一点:

一些生产者创建了 N 个队列(比方说foo.1 foo.2 foo.3)。比我在兔子的另一部分有一个消费者需要从所有 N 个(在我的示例 3 中)队列中获取消息。我知道我可以做这样的事情:

(method_frame, header_frame, body) = self.channel.basic_get(queue='foo.1', no_ack=False)
(method_frame, header_frame, body) = self.channel.basic_get(queue='foo.2', no_ack=False)
(method_frame, header_frame, body) = self.channel.basic_get(queue='foo.3', no_ack=False)

但是,如果我的消费者不知道这些名字怎么办,我真正想做的是:

(method_frame, header_frame, body) = self.channel.basic_get(queue='foo.*', no_ack=False)
4

3 回答 3

1

这是我所看到的:您需要从提供的数量n的队列中获取所有消息。根据我的个人经验,我只会编写一个 for 循环并通过添加来创建一个字符串"foo.%s" % (iteration)

这是我的意思的一个例子:

for i in range(queues):
    str = 'foo.%s' % (i)
    (method_frame, header_frame, body) = self.channel.basic_get(queue=str, no_ack=False)

只要你知道队列的数量,那么你就可以使用它。

于 2013-06-12T20:06:39.813 回答
1

如果您的消费者有一种识别队列的方法,您应该能够通过搜索找到它们foo.__dict__

您应该记住,如果您的任何队列设置在类级别,那么它们将不会出现在foo.__dict__. 在这种情况下,您将不得不编写一个遍历foo的 mro 的算法。

或者,如果您可以修改队列的创建,则可以通过使用某种管理器来跟踪它们。

class MyQueue(list):
    queues = {}  # Keeps track of all the queues out there

    @classmethod
    def add_to_producer(cls, obj, name, init_values):
        q = MyQueue(init_values)
        cls.queues[(obj, name)] = q
        setattr(obj, name, q)


class MyProducer(object):

    def __init__(self):
        # Initialize our producer with a couple of queues
        MyQueue.add_to_producer(self, 'a', [1,2])
        MyQueue.add_to_producer(self, 'b', [])


p1 = MyProducer()
p2 = MyProducer()
# Add another queue to p2
MyQueue.add_to_producer(p2, 'c', [4,5,6])

# Go through all of our created queues
for obj, attr_name in MyQueue.queues:
    if obj == p1:
        print 'p1', getattr(obj, attr_name)

    if obj == p2:
        print 'p2', getattr(obj, attr_name)

>>> p1 [1, 2]
>>> p1 []
>>> p2 [4, 5, 6]
>>> p2 [1, 2]
>>> p2 []
于 2013-06-12T20:09:03.063 回答
1

RabbitMQ 管理界面/api 将有权访问服务器上的所有队列。有一个易于使用的 Python 客户端PyRabbit可以让你get_queues。从那里你可以做任何你需要的过滤。

于 2013-06-12T20:59:53.873 回答