国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python隊列通信:rabbitMQ的使用(實例講解)

2020-02-16 11:17:11
字體:
來源:轉載
供稿:網友

(一)、前言

為什么引入消息隊列?

1.程序解耦

2.提升性能

3.降低多業務邏輯復雜度

(二)、python操作rabbit mq

rabbitmq配置安裝基本使用參見上節文章,不再復述。

若想使用python操作rabbitmq,需安裝pika模塊,直接pip安裝:

pip install pika

1.最簡單的rabbitmq producer端與consumer端對話:

producer:

#Author :ywqimport pikaauth=pika.PlainCredentials('ywq','qwe') #save auth indoconnection = pika.BlockingConnection(pika.ConnectionParameters(  '192.168.0.158',5672,'/',auth)) #connect to rabbitchannel = connection.channel() #create channelchannel.queue_declare(queue='hello') #declare queue#n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.channel.basic_publish(exchange='',   routing_key='hello',   body='Hello World!') #the body is the msg contentprint(" [x] Sent 'Hello World!'")connection.close()

consumer:

#Author :ywqimport pikaauth=pika.PlainCredentials('ywq','qwe') #auth infoconnection = pika.BlockingConnection(pika.ConnectionParameters(  '192.168.0.158',5672,'/',auth)) #connect to rabbitchannel = connection.channel()  #create channelchannel.queue_declare(queue='hello') #decalre queuedef callback(ch, method, properties, body): 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()

消息傳遞消費過程中,可以在rabbit web管理頁面實時查看隊列消息信息。

2.持久化的消息隊列,避免宕機等意外情況造成消息隊列丟失。

consumer端無需改變,在producer端代碼內加上兩個屬性,分別使消息持久化、隊列持久化,只選其一還是會出現消息丟失,必須同時開啟:

delivery_mode=2 #make msg persisdentdurable=True

屬性插入位置見如下代碼(producer端):

#Author :ywqimport pika,sysauth_info=pika.PlainCredentials('ywq','qwe')connection=pika.BlockingConnection(pika.ConnectionParameters(  '192.168.0.158',5672,'/',auth_info ))channel=connection.channel()channel.queue_declare(queue='test1',durable=True) #durable=Ture, make queue persistentmsg=''.join(sys.argv[1:]) or 'Hello'channel.basic_publish( exchange='', routing_key='test1', body=msg, properties=pika.BasicProperties(  delivery_mode=2 #make msg persisdent ))print('Send done:',msg)connection.close()

3.公平分發

在多consumer的情況下,默認rabbit是輪詢發送消息的,但有的consumer消費速度快,有的消費速度慢,為了資源使用更平衡,引入ack確認機制。consumer消費完消息后會給rabbit發送ack,一旦未ack的消息數量超過指定允許的數量,則不再往該consumer發送,改為發送給其他consumer。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 屯门区| 铁岭县| 黑龙江省| 蓬莱市| 盐边县| 宁乡县| 韶关市| 墨玉县| 孟津县| 阳新县| 永胜县| 兴宁市| 涟源市| 日土县| 霍山县| 汝阳县| 肇东市| 高陵县| 漳州市| 大名县| 普兰县| 正定县| 德昌县| 玛曲县| 高密市| 大埔县| 弥渡县| 安顺市| 剑阁县| 金秀| 西乌| 体育| 新竹市| 宣武区| 永川市| 奈曼旗| 松桃| 济南市| 德昌县| 沅陵县| 玉门市|