使用aioamqp一次从多个队列中进行消耗

时间:2016-08-10 09:53:34

标签: python rabbitmq python-asyncio

是否可以使用一个带有aioamqp的通道同时使用多个队列?

免责声明:我在项目问题跟踪器中创建了issue,但我真的很想知道我所做的事情是否有意义。

2 个答案:

答案 0 :(得分:1)

我认为此功能在AMQP协议中不可用(假设我对协议的理解是正确的)。

如果您希望从队列中消费,则必须在频道上发出basic.consume来电。此调用所需的参数为queue_name,并且它是"阻止" (不阻塞连接但阻塞通道)调用响应是队列中的对象。

长话短说:每个消费者在等待队列对象时必须拥有对频道的独占访问权。

好的,所以我最初的想法是错误的。在深入研究AMQP后,我发现它确实支持多个消费者通过一个渠道。但是,如果需要,它确实允许服务器设置其限制。不幸的是,我无法找到有关RabbitMQ特定案例的任何信息。所以我认为没有这样的限制。总而言之:这是图书馆的一个问题。

但是,解决方法仍然有效:只需为每个消费者创建一个频道。它应该工作得很好。

答案 1 :(得分:1)

ammoo有效:

import asyncio

from ammoo import connect


async def consume(channel, queue_name):
    async with channel.consume(queue_name, no_ack=True) as consumer:
        async for message in consumer:
            print('Message from {}: {}'.format(queue_name, message.body))
            if message.body == b'quit':
                print('Consumer for queue {} quitting'.format(queue_name))
                break


async def main():
    async with await connect('amqp://localhost/') as connection:
        async with connection.channel() as channel:
            await channel.declare_queue('queue_a')
            await channel.declare_queue('queue_b')

            await asyncio.gather(
                consume(channel, 'queue_a'),
                consume(channel, 'queue_b')
            )
            print('Both consumers are done')



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

输出:

# python3 test.py 
Message from queue_a: b'hello queue a'
Message from queue_b: b'hello queue b'
Message from queue_a: b'quit'
Consumer for queue queue_a quitting
Message from queue_b: b'another message for queue b'
Message from queue_b: b'quit'
Consumer for queue queue_b quitting
Both consumers are done

免责声明:我是图书馆的作者