2012-03-26 74 views
12

我正在python上运行代码,以发送和接收来自另一个应用程序的RabbitMQ队列,我无法允许线程。 这是非常新手的问题,但是,有没有可能只是检查是否有消息,如果没有任何,那么只是退出收听?我应该如何更改这个任务的基本“Hello world”示例?目前我设法停止消费,如果我收到一条消息,但如果没有消息,我的方法receive()会继续等待。如何强制它不等待如果没有消息?或者也许只等待一段时间?RabbitMQ消费一个消息,如果存在并退出

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 
+0

红宝石API必须检查队列的长度的方法..你检查Python文档? – 2012-03-26 18:04:37

回答

15

好吧,我发现了以下解决方案:

def receive(): 
    parameters = pika.ConnectionParameters(RabbitMQ_server) 
    connection = pika.BlockingConnection(parameters) 
    channel = connection.channel() 
    channel.queue_declare(queue='toM') 
    method_frame, header_frame, body = channel.basic_get(queue = 'toM')   
    if method_frame.NAME == 'Basic.GetEmpty': 
     connection.close() 
     return '' 
    else:    
     channel.basic_ack(delivery_tag=method_frame.delivery_tag) 
     connection.close() 
     return body 
+0

检查method_frame是否也应该很重要。如果队列中没有更多消息,则channel.basic_get(queue ='toM')将返回None-s。 – balas 2015-06-06 21:03:17