如果存在则RabbitMQ消耗一条消息并退出

时间:2012-03-26 16:45:36

标签: python rabbitmq amqp

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

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

1 个答案:

答案 0 :(得分:20)

好的,我找到了以下解决方案:

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