超时无法通过pika.Blocking连接发送

时间:2012-04-27 12:24:27

标签: python pika

我正在尝试编写一个客户端程序来接收来自rabbitmq服务器,我想用它来设置超时。在指定的时间之后,客户端应该停止使用队列中的消息并退出。

我正在使用阻挡连接的鼠兔。我看到阻塞连接中定义的add_timeout(延迟,回调),但是当我尝试使用它时,我收到以下错误,如下所示。

 [*] Waiting for logs. To exit press CTRL+C
Traceback (most recent call last):
  File "/root/workspace/Misc/misc/pika_samples/log_recieve.py", line 39, in <module>
    channel.start_consuming()
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 293, in start_consuming
    self.transport.connection.process_data_events()
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 103, in process_data_events
    self.process_timeouts()
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 160, in process_timeouts
    self._timeouts[timeout_id]['handler']()
TypeError: callback() takes exactly 4 arguments (0 given)

这是我的客户端程序。我没有运行任何服务器来模拟超时条件。

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = "#"
for binding_key in binding_keys:
    channel.queue_bind(exchange='topic_logs',queue=queue_name,
                   routing_key=binding_key)

print ' [*] Waiting for logs. To exit press CTRL+C'
def callback(ch, method, properties, body):
    print " [x] %r:%r" % (method.routing_key, body,)
    channel.stop_consuming()
connection.add_timeout(10, callback)
channel.basic_consume(callback,queue=queue_name,no_ack=True)
channel.start_consuming()

如果我在指定的超时期限内收到消息,则客户端应该打印消息,并且应该停止进一步消费。

有人可以帮我解决如何在客户端设置超时的问题吗?

1 个答案:

答案 0 :(得分:0)

截止日期中的这个问题。然后截止日期发生函数回调调用没有任何args。所以你可以改变你的代码

def callback(ch=None, method=None, properties=None, body=None):
    if ch is None or method is None or properties is None or body is None:
         print "Deadline"
    else:
         print " [x] %r:%r" % (method.routing_key, body,)