用于RabbitMQ的Kombu在取消@by_queue之后不会调用回调方法

时间:2016-04-24 12:18:44

标签: python rabbitmq kombu

我从RabbitMQ写了一个简单的队列使用者(使用kombu):

import socket
from kombu import Connection, Exchange, Queue

def handle_message(payload, message):
   payload = int(message.payload)
   index = payload % 1000
   print('queue%s: ' %(index+1) + message.payload)
   message.ack()

while True:
    try:
        # connections
        with Connection('amqp://1000:1000@localhost:5672//1000') as conn:

            while True:
                chan = conn.channel()
                chan.basic_qos(prefetch_size=0, prefetch_count=10, a_global=False)

                with conn.Consumer(channel=chan,  callbacks=[handle_message]) as consumer:
                    queue = Queue('queue1', routing_key='queue1', exchange=Exchange())
                    consumer.add_queue(queue)
                    consumer.consume()

                    try:
                        print('before drain_events')
                        conn.drain_events(timeout=5)
                        print('after drain_events')

                        consumer.cancel_by_queue('queue1')
                        if not consumer.consuming_from('queue1'):
                            consumer.recover(requeue=True)
                    except socket.timeout as e:
                        print('timeout')

    except Exception as e:
        print("An exception was caught %s", e.message);

在此代码中,我向使用者添加一个队列(“queue1”)并开始使用它,并在每个drain_event使用cancel_by_queue删除队列之后。

我得到的结果是在第一轮drain_event中调用了回调“handle_message”,但是在下一次迭代中没有。 我用错了吗?

输出:

before drain_events
queue1: 6221
after drain_events
before drain_events
after drain_events
before drain_events
after drain_events
before drain_events
after drain_events
before drain_events
.
.
.

如果我把

with Connection('amqp://1000:1000@localhost:5672//1000') as conn:

内部循环内部工作 - 但我不希望每次删除队列并再次开始使用它时都会创建一个新连接。

由于

参见Yaniv

0 个答案:

没有答案