文档
RabbitMQ Hello World - Python (pika)
目标
演示最基本的消息发送(Producer)和接收(Consumer)流程,使用 Direct Exchange + 默认队列。
环境准备
pip install pika
完整代码
发送端(producer.py)
import pika
# 建立连接
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost', port=5672)
)
channel = connection.channel()
# 声明队列(幂等操作)
channel.queue_declare(queue='hello')
# 发送消息
channel.basic_publish(
exchange='',
routing_key='hello',
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2, # 消息持久化
)
)
print("[x] Sent 'Hello World!'")
connection.close()
接收端(consumer.py)
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost', port=5672)
)
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(f"[x] Received {body}")
ch.basic_ack(delivery_tag=method.delivery_tag) # 手动确认
# 公平分发:每次只取一条
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue='hello',
on_message_callback=callback,
auto_ack=False # 手动 ACK
)
print('[*] Waiting for messages. Press CTRL+C to exit.')
channel.start_consuming()
运行步骤
# 终端1:启动消费者
python consumer.py
# 终端2:发送消息
python producer.py
预期输出
- 生产者终端:
[x] Sent 'Hello World!' - 消费者终端:
[x] Received b'Hello World!'