实现一个简单模式
-
首先需要把RabbitMQ跑起来
rabbitmq-server.bat
2. 实现一个生产者模式
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# 声明一个管道
channel = connection.channel()
# 声明queue,这个队列在RabbitMQ中生成,发送方和接收方使用同一个队列
channel.queue_declare(queue='hello2', durable=True)
# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='', # 交换机模式
routing_key='hello', # 队列名称
body='我真机智啊!',
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
)
) # body消息内容
print(" [x] Sent 'Hello World!'")
connection.close()
-
消费者模式
#!/usr/bin/env python import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() # 因为不确定是生产者先启动,还是消费者先启动 channel.queue_declare(queue='hello') # 回调函数 def callback(ch, method, properties, body): print(" [x] Received %r" % body) # 告诉RabbitMQ这个回调函数从hello中的队列获取数据 channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') # 绑定RabbitMQ队列 channel.start_consuming()