官方教程:https://www.rabbitmq.com/tutorials/tutorial-one-python.html
生产者 send.py
#!/usr/bin/env python
import pika
# 连接 RabbitMQ server
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 创建一个名为 hello 的队列
channel.queue_declare(queue='hello')
# 消息先到 exchange,再到 queue。exchange 为空字符串,说明使用默认的 exchange,这样就可以直接指明 queue 了
# routing_key 指明 queue
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
# 关闭连接
connection.close()
消费者 receive.py
#!/usr/bin/env python
import pika
# 连接 RabbitMQ server
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# 如果生产者已经创建过了,则不会创建
channel.queue_declare(queue='hello')
# 只要接收到消息,就会被 Pika 自动调用
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 告诉 RabbitMQ,callback 从 “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()
运行结果:
$ python3 receive.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'Hello World!'
$ python3 send.py
[x] Sent 'Hello World!'