Python RabbitMQ 订阅消费

一、什么是 RabbitMQ?

RabbitMQ 是一个开源的消息代理软件,用于在应用程序之间传送消息。它实现了高级消息队列协议(AMQP)标准,能够在分布式系统中可靠地传递消息。

二、为什么要使用 RabbitMQ?

在分布式系统中,不同的应用程序需要进行通信和协作。使用 RabbitMQ 可以实现异步通信,提高系统的可靠性和性能。通过消息队列,发送方和接收方可以解耦,降低系统的耦合度。

三、如何在 Python 中使用 RabbitMQ?

1. 安装 pika 库
pip install pika
  • 1.
2. 生产者示例
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello, RabbitMQ!')
print(" [x] Sent 'Hello, RabbitMQ!'")

connection.close()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
3. 消费者示例
import pika

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

四、如何订阅消费消息?

在 RabbitMQ 中,消费者通过订阅队列来接收消息。当消息到达队列时,RabbitMQ 会将消息推送给订阅该队列的消费者。

1. 创建订阅者
import pika

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs', exchange_type='fanout')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(exchange='logs', queue=queue_name)

channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
2. 生产者示例
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = 'Hello, subscribers!'
channel.basic_publish(exchange='logs', routing_key='', body=message)

print(" [x] Sent %r" % message)

connection.close()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

五、总结

通过本文的介绍,我们了解了 RabbitMQ 的基本概念和使用方法,在 Python 中实现了生产者和消费者的示例,并通过订阅消费的方式实现了消息的广播。RabbitMQ 是一个强大的消息代理软件,能够帮助我们构建高效的分布式系统,提高系统的可靠性和性能。

希望本文对您有所帮助,谢谢阅读!

六、参考

  • [RabbitMQ 官方文档](
  • [pika Python 库](