python - RabbitMQ 消耗一条消息(如果存在)并退出

标签 python rabbitmq amqp

我在 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/

相关文章:

ruby - 为消息队列实现类似 "leaky bucket"的算法

concurrency - 将 celery 并发设置为每个队列 1 个 worker

Azure IoT 中心 AMQP 通信多路复用

amqp - ThreadChannelConnectionFactory 是否应该与 RabbitAdmin 自动声明兼容?

python - 动态加载库的 CMake 输出名称?

C# Regex "Verbose"就像在 Python 中一样

python - 如何使用多个模板实现 Django session 向导

python - 仅显示 pandas 中日期范围行的交集

node.js - RabbitMQ 是否有相当于 "ping"的值?如何诊断交换器或队列是否正在广播?

Angular 10 : Buffer is not defined