使用Pika clien轮询RabbitMQ消息

2024-09-26 22:10:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python创建RabbitMQ接收器/使用者,但不确定如何检查消息。我试着在我自己的循环中做这个,而不是使用pika中的回调。在

如果我理解了一些事情,那么在Java客户机中,我可以使用getBasic()来检查是否有任何消息可以不阻塞地使用。我不介意在收到消息时阻止,但我不想在有消息之前阻止。在

我没有找到任何明确的例子,也没有找到相应的调用pika。在


Tags: 消息客户机rabbitmq使用者java事情pika例子
3条回答

如果你想同步进行,那么你需要看看鼠兔BlockingConnection

The BlockingConnection creates a layer on top of Pika’s asynchronous core providng methods that will block until their expected response has returned. Due to the asynchronous nature of the Basic.Deliver and Basic.Return calls from RabbitMQ to your application, you are still required to implement continuation-passing style asynchronous methods if you’d like to receive messages from RabbitMQ using basic_consume or if you want to be notified of a delivery failure when using basic_publish.

更多信息和示例

https://pika.readthedocs.org/en/0.9.12/connecting.html#blockingconnection

您可以使用以下答案的示例定期检查队列大小Get Queue Size in Pika (AMQP Python)

队列处理循环可以在process_data_events()的帮助下迭代完成:

import pika

# A stubborn callback that still wants to be in the code.
def mq_callback(ch, method, properties, body):
    print(" Received: %r" % body)

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
queue_state = channel.queue_declare(queue="test")
# Configure a callback.
channel.basic_consume(mq_callback, queue="test")

try:
    # My own loop here:
    while(True):
        # Do other processing

        # Process message queue events, returning as soon as possible.
        # Issues mq_callback() when applicable.
        connection.process_data_events(time_limit=0)
finally:
    connection.close()

相关问题 更多 >

    热门问题