python - Rabbitmq:channel.start_consuming()不会消耗

标签 python rabbitmq pika

我正在使用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 是一个 worker :

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 将真正开始监听要使用的消息。

关于python - Rabbitmq:channel.start_consuming()不会消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28713820/

相关文章:

python - 有没有办法在 Django 中重新加载后保留 html 复选框状态?

node.js - SocketIO 扩展架构和大房间需求

docker - 无法使用 dockerized spring boot 应用程序创建 RabbitMq 交换

python - 如何添加 header 键 :value pair when publishing a message with pika

python-3.x - RabbitMQ Pika 连接重置 , (-1, ConnectionResetError(104, 'Connection reset by peer' ))

rabbitmq - RabbitMQ 中的 key 感知消费者

c++ - 不同编程语言的getters和setters的使用

python - pandas groupby 中的聚合函数是否以不同方式处理内置函数?

python - Django 找不到 URL 模式

ruby - 为消息队列实现类似 "leaky bucket"的算法