【问题标题】:How to check if there is no message in RabbitMQ with Pika and Python如何使用 Pika 和 Python 检查 RabbitMQ 中是否没有消息
【发布时间】:2018-10-05 09:14:52
【问题描述】:

我使用 pika python 库从 RabbitMQ 读取消息。在循环中读取消息由

connection = rpc.connect()
channel = connection.channel()
channel.basic_consume(rpc.consumeCallback, queue=FromQueue, no_ack=Ack)
channel.start_consuming()

这很好用。 但我也需要阅读一条消息,我会这样做:

method, properties, body = channel.basic_get(queue=FromQueue)
rpc.consumeCallback(Channel=channel,Method=method, Properties=properties,Body=body)

但是,当队列中没有消息时,脚本就会出现问题。如何实现 here 描述的 get_empty() 方法?

【问题讨论】:

  • channel.start_consuming 被阻止。你怎么能打电话给channel.basic_get?您是否使用单独的线程?
  • 不,我使用其中任何一个。这是一个决定使用哪一个的参数。

标签: python-3.x rabbitmq python-pika


【解决方案1】:

我通过检查以下响应暂时解决了这个问题:

method, properties, body = channel.basic_get(queue=FromQueue)
if(method == None):
    ## queue is empty

【讨论】:

    【解决方案2】:

    你可以像这样检查正文中的空:

    def callback(ch, method, properties, body):
        decodeBodyInfo = body.decode('utf-8')
        if decodeBodyInfo != '':
            cacheResult = decodeBodyInfo
            ch.stop_consuming()
    

    如此简单易用:D

    【讨论】:

      【解决方案3】:

      如果您在 for 循环中使用 channel.consume 生成器,您可以设置 inactivity_timeout 参数。

      来自 pika 文档,

      :param float inactivity_timeout: if a number is given (in seconds), will cause the
      method to yield (None, None, None) after the given period of inactivity; this 
      permits for pseudo-regular maintenance activities to be carried out by the user 
      while waiting for messages to arrive. If None is given (default), then the method 
      blocks until the next event arrives. NOTE that timing granularity is limited by the 
      timer resolution of the underlying implementation.NEW in pika 0.10.0.
      

      因此将代码更改为类似这样可能会有所帮助

              for method_frame, properties, body in channel.consume(queue, inactivity_timeout=120):
      
                  # break of the loop after 2 min of inactivity (no new item fetched)
                  if method_frame is None
                      break
      

      退出循环后不要忘记正确处理通道和连接

      【讨论】:

        猜你喜欢
        • 2012-10-13
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2013-02-14
        • 2021-06-23
        • 2012-11-07
        相关资源
        最近更新 更多