Rabbitmq:channel.start_consuming() 不会消耗

Rabbitmq: channel.start_consuming() wont consume

我正在使用 rabbitmq。代码卡在 channel.start_consuming()。队列中有消息。

可能是什么问题。当我使用 ctrl+C 强行结束代码时:

INFO:pika.adapters.base_connection:Connecting fd 4 to localhost:5672
INFO:pika.adapters.blocking_connection:Adapter connected
 [*] Waiting for messages. To exit press CTRL+C



^CTraceback (most recent call last):
  File "recipe_code.py", line 293, in <module>
    channel.start_consuming()
  File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 722, in start_consuming
    self.connection.process_data_events()
  File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 88, in process_data_events
    if self._handle_read():
  File "/usr/local/lib/python2.7/dist-packages/pika/adapters/blocking_connection.py", line 184, in _handle_read
    super(BlockingConnection, self)._handle_read()
  File "/usr/local/lib/python2.7/dist-packages/pika/adapters/base_connection.py", line 296, in _handle_read
    data = self.socket.recv(self._buffer_size)
KeyboardInterrupt

recipe_code.py是工人:

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='myqueue', durable=True)
print ' [*] Waiting for messages. To exit press CTRL+C'

def callback(ch, method, properties, body):

//do some work//

  ch.basic_ack(delivery_tag = method.delivery_tag)

  channel.basic_qos(prefetch_count=1)
  channel.basic_consume(callback,queue='myqueue')

channel.start_consuming()

我在您的代码中看到的唯一问题是 basic_qosbasic_consume 上的缩进。如果您发布的代码是正确的,那两个函数将永远不会被调用。

connection = \
    pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()


def callback(ch, method, properties, body):
    print "Message:", body
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.queue_declare(queue='myqueue', durable=True)
# You had an unwanted indent here.
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback, queue='myqueue')

print ' [*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()

您打印的消息也应该在 start_consuming 行的正上方,因为那时 pika 将真正开始侦听要使用的消息。