(一)、前言
為什么引入消息隊列?
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。
新聞熱點
疑難解答