我在 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
最佳答案
好的,我找到了以下解决方案:
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
关于python - RabbitMQ 消耗一条消息(如果存在)并退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9876227/