Python-RabbitMQ(簡單發送模型)

來源:互聯網
上載者:User

標籤: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(簡單發送模型)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.