RabbitMQ的发送与消费测试

发送

python 复制代码
import pika
import sys

# 硬编码参数,明确打印出来让你亲眼确认
HOST = '127.0.0.1'
PORT = 5672  # 明确写死为 5672

print(f"🔗 正在连接 {HOST}:{PORT} ...")

connection = pika.BlockingConnection(
    pika.ConnectionParameters(
        host=HOST,
        port=PORT,          # 这里绝对不可能错
        virtual_host='/',
        credentials=pika.PlainCredentials('guest', 'guest')
    )
)
channel = connection.channel()

# 声明队列(使用 durable=True 避开 541 错误)
channel.queue_declare(queue='hello_world', durable=True)

message = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else "Hello World!"
channel.basic_publish(
    exchange='',
    routing_key='hello_world',
    body=message,
    properties=pika.BasicProperties(delivery_mode=2)
)
print(f"✅ 发送成功: {message}")
connection.close()

消费

python 复制代码
import pika

# 1. 建立连接(必须和发送端参数完全一致)
connection = pika.BlockingConnection(
    pika.ConnectionParameters(
        host='127.0.0.1',
        port=5672,
        virtual_host='/',
        credentials=pika.PlainCredentials('guest', 'guest')
    )
)
channel = connection.channel()

# 2. 声明队列(幂等操作,确保队列存在;参数必须与发送端一致)
channel.queue_declare(queue='hello_world', durable=True)

print("⏳ 正在等待消息... (按 Ctrl+C 退出)")

# 3. 定义处理函数:收到消息时会自动调用这个函数
def callback(ch, method, properties, body):
    # body 是 bytes 类型,需要 decode 成字符串
    print(f"📩 收到消息: {body.decode()}")

# 4. 告诉 RabbitMQ 从 'hello_world' 队列取消息,交给 callback 处理
# auto_ack=True 表示收到后自动告诉服务器删除消息(简单场景够用)
channel.basic_consume(
    queue='hello_world',
    on_message_callback=callback,
    auto_ack=True
)

# 5. 开始循环接收(这里会阻塞,一直监听)
channel.start_consuming()

测试

打开两个控制台,然后先打开消费,再运行发送