python pika簡單實現RabbitMQ通信
阿新 • • 發佈:2018-05-17
oca rec brush utf sage odin 安裝 回調 def
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啟動客戶端向消息隊列發送消息。
python pika簡單實現RabbitMQ通信