Python pika简单实现RabbitMQ通信

Windows上安装及启动RabbitMQ

https://blog.csdn.net/hzw19920329/article/details/53156015

安装python pika库

pip install pika

编写发送消息client.py

 1 # coding:utf8
 2 
 3 import pika
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))  # 创建一个连接
 6 channel = connection.channel()  # 创建通道
 7 channel.queue_declare(queue='hello')  # 把消息队列的名字为hello
 8 channel.basic_publish(exchange='',
 9                       routing_key='hello',
10                       body='hello world!')  # 设置routing_key(消息队列的名称)和body(发送的内容)
11 print(" [x] sent 'Hello World!'")
12 connection.close()  # 关闭连接

编写监听消息队列server.py

 1 # coding:utf8
 2 
 3 import pika
 4 
 5 connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))  # 创建一个连接
 6 channel = connection.channel()  # 建立通道
 7 channel.queue_declare(queue='hello')  # 把消费者和queue绑定起来,生产者和queue的也是hello
 8 
 9 
10 def callback(ch, method, properties, body):  # 回调函数get消息体
11     print(" [x] Received %r" % body)
12 
13 
14 channel.basic_consume(callback,
15                       queue='hello',
16                       no_ack=True)
17 
18 print(' [*] Waiting for messages. To exit press CTRL+C')
19 channel.start_consuming()  # 创建死循环,监听消息队列,可使用CTRL+C结束监听

 

执行server.py可以监听消息队列,执行client.py启动客户端向消息队列发送消息。

 

posted @ 2018-05-16 23:08  reboot777  阅读(225)  评论(0编辑  收藏  举报