484 字
2 分钟
Python RabbitMQ 入门简单使用
RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件)。RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的。所有主要的编程语言均有与代理接口通讯的客户端库。
首先要安装运行 RabbitMQ 服务, (RabbitMQ 依赖于 Erlang 环境, 所以还要装 Erlang), Erlang与RabbitMQ,安装路径都应不含空格符。
下载地址: Installing RabbitMQ | RabbitMQ
安装
pip install pika消费者 consumer.py
import pika
# 创建一个连接credentials = pika.PlainCredentials('guest', 'guest')parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)
connection = pika.BlockingConnection(parameters)channel = connection.channel()# 声明一个队列, durable=True表示队列持久化channel.queue_declare(queue='hello', durable=True)
def callback(ch, method, properties, body): print("Received message:", body)
channel.basic_consume(queue='hello', # 指定消费的队列 auto_ack=True, # 自动确认消息 on_message_callback=callback)
# 当我们启动消费者时,我们就开启了一个永远不会停止的循环,消费者等待数据并调用回调函数,我们通过捕获KeyboardInterrupt来停止程序print("Waiting for messages. To exit press CTRL+C")channel.start_consuming()生产者 producer.py
import time
import pika
# 创建一个连接credentials = pika.PlainCredentials('guest', 'guest')parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)connection = pika.BlockingConnection(parameters)# 创建一个频道channel = connection.channel()# 消费者那里已经声明了队列,这里不需要再重复声明# channel.queue_declare(queue='hello', durable=True)
# 在RabbitMQ中,消息不能直接发送到队列,通常需要需要一个exchange, 这里使用默认的exchange# exchange用来准确指定我们的消息撒送到哪个queue,queue的名称需要在routing_key中声明for i in range(100): # 发布消息 channel.basic_publish(exchange='', routing_key='hello', body=f'{i} Hello World!') print(f" [x] Sent {i} Hello World!") time.sleep(.5)# 关闭连接connection.close()运行结果

GUI管理工具:
RabbitMQ Assistant - RabbitMQ可视化管理与监控工具 (redisant.cn)
启动服务后, 访问 http://localhost:15672/# 也有GUI界面
参考:
Python RabbitMQ 入门简单使用
https://blog.tiamix.cn/posts/python-rabbitmq-入门/