【问题标题】:RabbitMQ consume one message if exists and quitRabbitMQ 如果存在则使用一条消息并退出
【发布时间】: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 文档吗?

标签: python rabbitmq amqp


【解决方案1】:

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

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

【讨论】:

  • 检查 method_frame 是否为 None 也应该很重要。如果队列中没有更多消息,channel.basic_get(queue = 'toM') 将返回 None-s。
  • @GrayR 有没有办法做到这一点并在完成后确认消息?
  • method_frame.NAME 对于 pika >0.10.0 似乎不存在。只需测试 if method_frame is None: 即可在 pika 1.1.0 上正常工作
猜你喜欢
  • 2020-02-18
  • 2019-11-24
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2014-01-08
  • 1970-01-01
  • 2015-12-02
相关资源
最近更新 更多