【发布时间】:2012-03-26 16:45:36
【问题描述】:
我在 python 上运行代码以从另一个我不能允许线程的应用程序的 RabbitMQ 队列发送和接收。 这是一个非常新手的问题,但是,是否有可能只检查是否有消息,如果没有,那么就退出收听吗?我应该如何更改此类任务的基本“Hello world”示例?目前,如果我收到一条消息,我已经设法停止消费,但如果没有消息,我的方法 receive() 就继续等待。如果没有消息,如何强制它不等待?或者也许只等待给定的时间?
import pika
global answer
def send(msg):
connection = pika.BlockingConnection(pika.ConnectionParameters())
channel = connection.channel()
channel.queue_declare(queue='toJ')
channel.basic_publish(exchange='', routing_key='toJ', body=msg)
connection.close()
def receive():
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='toM')
channel.basic_consume(callback, queue='toM', no_ack=True)
global answer
return answer
def callback(ch, method, properties, body):
ch.stop_consuming()
global answer
answer = body
【问题讨论】:
-
ruby API 有一个检查队列长度的方法。你检查过 python 文档吗?