国产探花免费观看_亚洲丰满少妇自慰呻吟_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。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兴化市| 绍兴县| 济阳县| 威信县| 灌阳县| 阿合奇县| 山丹县| 横峰县| 岗巴县| 凤山市| 巍山| 信丰县| 读书| 望江县| 浦县| 明星| 吉安县| 丁青县| 盐津县| 五台县| 宁津县| 辉县市| 乡城县| 武安市| 临海市| 巴青县| 香格里拉县| 常德市| 岗巴县| 澄城县| 苍溪县| 元朗区| 特克斯县| 张家口市| 宝山区| 淄博市| 赤水市| 湾仔区| 克东县| 龙山县| 锦屏县|