標籤:method highlight 本機 模型 消費者 情況 close host 接收
RabbitMQ需要 erlang 和pika
發送端:生產者
import pikaconnection = pika.BlockingConnection( pika.ConnectionParameters(‘localhost‘))channel =connection.channel()#聲明一個管道,在管道裡發訊息#聲明queuechannel.queue_declare(queue=‘hello‘)#在管道裡還得聲明一個隊列channel.basic_publish(exchange=‘‘, routing_key=‘hello‘,#就是列隊queue名字 body=‘Hello World‘#訊息內容 )print(" [x] Sent ‘Hello World!‘")connection.close()#不用關閉管道,關閉串連就行
接收端:消費者
import pika# 建立到達RabbitMQ Server的connection# 此處RabbitMQ Server位於本機-localhostconnection = pika.BlockingConnection(pika.ConnectionParameters( host=‘localhost‘))channel = connection.channel()# 聲明queue,確認要從中接收message的queue# queue_declare函數是等冪的,可運行多次,但只會建立一次# 若可以確信queue是已存在的,則此處可省略該聲明,如producer已經產生了該queue# 但在producer和consumer中重複聲明queue是一個好的習慣channel.queue_declare(queue=‘hello‘)print(‘ [*] Waiting for messages. To exit press CTRL+C‘)# 定義回呼函數# 一旦從queue中接收到一個message回呼函數將被調用# ch:channel# method:# properties:# body:messagedef callback(ch, method, properties, body): print(" [x] Received %r" % body)# 從queue接收message的參數設定# 包括從哪個queue接收message,用於處理message的callback,是否要確認message# 預設情況下是要對訊息進行確認的,以防止訊息丟失。# 此處將no_ack明確指明為True,不對訊息進行確認。channel.basic_consume(callback, queue="hello", no_ack=True)# 開始迴圈從queue中接收message並使用callback進行處理channel.start_consuming()
Python-RabbitMQ(簡單發送模型)