Windows上安装及启动RabbitMQ
https://blog.csdn.net/hzw19920329/article/details/53156015
安装python pika库
pip install pika
编写发送消息client.py
# coding:utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) # 创建一个连接
channel = connection.channel() # 创建通道
channel.queue_declare(queue='hello') # 把消息队列的名字为hello
channel.basic_publish(exchange='',
routing_key='hello',
body='hello world!') # 设置routing_key(消息队列的名称)和body(发送的内容)
print(" [x] sent 'Hello World!'")
connection.close() # 关闭连接
编写监听消息队列server.py
# coding:utf8 import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) # 创建一个连接
channel = connection.channel() # 建立通道
channel.queue_declare(queue='hello') # 把消费者和queue绑定起来,生产者和queue的也是hello def callback(ch, method, properties, body): # 回调函数get消息体
print(" [x] Received %r" % body) channel.basic_consume(callback,
queue='hello',
no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() # 创建死循环,监听消息队列,可使用CTRL+C结束监听
执行server.py可以监听消息队列,执行client.py启动客户端向消息队列发送消息。