docker中安装
docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management
- 必须使用management版本才能使用web管理工具
http://127.0.0.1:15672
生产者
import pika
import random
import time
# 新建连接,rabbitmq安装在本地则hostname为'localhost'
hostname = '127.0.0.1'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)
# 创建通道
channel = connection.channel()
# 声明一个队列 durable=True 为持久化存储
channel.queue_declare(queue='hello', durable=True)
def send():
while True:
number = random.randint(1, 1000)
body = str(number)
# 参数: 交换机; 队列名,写明将消息发往哪个队列; 消息内容; 持久化存储
# routing_key在使用匿名交换机的时候才需要指定,表示发送到哪个队列
channel.basic_publish(exchange='', routing_key='hello', body=body, properties=pika.BasicProperties(delivery_mode=2,))
send()
connection.close()
消费者
import pika
hostname = '127.0.0.1'
parameters = pika.ConnectionParameters(hostname)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# 持久化存储生产消费都要加 durable=True
channel.queue_declare(queue='hello', durable=True)
def callback(ch, method, properties, body):
print('res', body)
# 告诉rabbitmq使用callback来接收信息 最后一个参数不知道是啥
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()