消息隊列之RabbitMQ

RabbitMQ

什麼叫消息隊列

消息(Message)是指在應用間傳送的數據。消息能夠很是簡單,好比只包含文本字符串,也能夠更復雜,可能包含嵌入對象。python

消息隊列(Message Queue)是一種應用間的通訊方式,消息發送後能夠當即返回,由消息系統來確保消息的可靠傳遞。消息發佈者只管把消息發佈到 MQ 中而不用管誰來取,消息使用者只管從 MQ 中取消息而不論是誰發佈的。這樣發佈者和使用者都不用知道對方的存在。服務器

爲什麼用消息隊列

從上面的描述中能夠看出消息隊列是一種應用間的異步協做機制,那何時須要使用 MQ 呢?負載均衡

以常見的訂單系統爲例,用戶點擊【下單】按鈕以後的業務邏輯可能包括:扣減庫存、生成相應單據、發紅包、發短信通知。在業務發展初期這些邏輯可能放在一塊兒同步執行,隨着業務的發展訂單量增加,須要提高系統服務的性能,這時能夠將一些不須要當即生效的操做拆分出來異步執行,好比發放紅包、發短信通知等。這種場景下就能夠用 MQ ,在下單的主流程(好比扣減庫存、生成相應單據)完成以後發送一條消息到 MQ 讓主流程快速完結,而由另外的單獨線程拉取MQ的消息(或者由 MQ 推送消息),當發現 MQ 中有發紅包或發短信之類的消息時,執行相應的業務邏輯。異步

RabbitMQ 

RabbitMQ 是一個由 Erlang 語言開發的 AMQP 的開源實現。

rabbitMQ是一款基於AMQP協議的消息中間件,它可以在應用之間提供可靠的消息傳輸。在易用性,擴展性,高可用性上表現優秀。使用消息中間件利於應用之間的解耦,生產者(客戶端)無需知道消費者(服務端)的存在。並且兩端可使用不一樣的語言編寫,大大提供了靈活性。ide

 

中文文檔函數

rabbitMQ安裝

 for Linux:
複製代碼
安裝配置epel源
   $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
 
安裝erlang
   $ yum -y install erlang
 
安裝RabbitMQ
   $ yum -y install rabbitmq-server
複製代碼
注意:service rabbitmq-server start/stop

rabbitMQ工做模型

簡單模式

示例

# ######################### 生產者 #########################
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
# ########################## 消費者 ##########################
 connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') def 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()

相關參數

(1)no-ack = False,若是消費者遇到狀況(its channel is closed, connection is closed, or TCP connection is lost)掛掉了,那麼,RabbitMQ會從新將該任務添加到隊列中。post

  • 回調函數中的ch.basic_ack(delivery_tag=method.delivery_tag)
  • basic_comsume中的no_ack=False

消息接收端應該這麼寫:性能

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='10.211.55.4'))
channel = connection.channel()
channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    import time
    time.sleep(10)
    print 'ok'
    ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=False)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

(2)  durable  :消息不丟失fetch

# 生產者
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello1', durable=True)
channel.basic_publish(exchange='',
routing_key='hello1',
body='Hello World%s!',
properties=pika.BasicProperties(delivery_mode=2)) # make message persistent

print(" [x] Sent 'Hello World!'")
connection.close()
# 消費者
import pika
 
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello1', durable=True)


def callback(ch, method, properties, body):
# exit()
print(" [x] Received %r" % body)
# 若是有消費者掛了可使用,
# no_ack = False
ch.basic_ack(delivery_tag=method.delivery_tag) # 回饋機制打開,打開此行


channel.basic_consume(callback,
queue='hello1',
no_ack=False) # 回饋機制打開

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
 
 

(3) 消息獲取順序

默認消息隊列裏的數據是按照順序被消費者拿走,例如:消費者1 去隊列中獲取 奇數 序列的任務,消費者1去隊列中獲取 偶數 序列的任務。

channel.basic_qos(prefetch_count=1) 表示誰來誰取,再也不按照奇偶數排列

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()

# make message persistent
channel.queue_declare(queue='hello')


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
    import time
    time.sleep(10)
    print 'ok'
    ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=False)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

exchange模型

3.1 發佈訂閱

發佈訂閱和簡單的消息隊列區別在於,發佈訂閱會將消息發送給全部的訂閱者,而消息隊列中的數據被消費一次便消失。因此,RabbitMQ實現發佈和訂閱時,會爲每個訂閱者建立一個隊列,而發佈者發佈消息時,會將消息放置在全部相關隊列中。

exchange type = fanout
# 生產者
#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
                         exchange_type='fanout') # 建立一個channel 而後聲明其爲exchange模式 生產者或消費者哪一個先運行,誰先建立(在rabbitmq中建立)

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',   # 將數據寫入到exchange中
                      routing_key='',
                      body=message)
print(" [x] Sent %r" % message)
connection.close()


# 消費者
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
                         exchange_type='fanout')  # 同生產者

result = channel.queue_declare(exclusive=True)  # 在channel聲明並聲明一個訂閱者隊列
queue_name = result.method.queue  # 自動給queue起個名字

channel.queue_bind(exchange='logs',   # 將剛纔聲明的queue與exchange綁定
                   queue=queue_name)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r" % body)

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

 3.2 關鍵字發送

 exchange type = direct

以前事例,發送消息時明確指定某個隊列並向其中發送消息,RabbitMQ還支持根據關鍵字發送,即:隊列綁定關鍵字,發送者將數據根據關鍵字發送到消息exchange,exchange根據 關鍵字 斷定應該將數據發送至指定隊列。

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs',
                       queue=queue_name,
                       routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

消費者
消費者
#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='direct_logs',
                         type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='direct_logs',
                      routing_key=severity,
                      body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()

生產者
生產者

 

3.3 模糊匹配

 exchange type = topic

發送者路由值              隊列中
old.boy.python          old.*  -- 不匹配
old.boy.python          old.#  -- 匹配

在topic類型下,可讓隊列綁定幾個模糊的關鍵字,以後發送者將數據發送到exchange,exchange將傳入」路由值「和 」關鍵字「進行匹配,匹配成功,則將數據發送到指定隊列。

  • # 表示能夠匹配 0 個 或 多個 單詞
  • *  表示只能匹配 一個 單詞

 示例:

#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='topic_logs',
                         type='topic')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

binding_keys = sys.argv[1:]
if not binding_keys:
    sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    sys.exit(1)

for binding_key in binding_keys:
    channel.queue_bind(exchange='topic_logs',
                       queue=queue_name,
                       routing_key=binding_key)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

消費者
消費者
#!/usr/bin/env python
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='topic_logs',
                         type='topic')

routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='topic_logs',
                      routing_key=routing_key,
                      body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()

生產者
生產者

 基於RabbitMQ的RPC

Callback queue 回調隊列

一個客戶端向服務器發送請求,服務器端處理請求後,將其處理結果保存在一個存儲體中。而客戶端爲了得到處理結果,那麼客戶在向服務器發送請求時,同時發送一個回調隊列地址reply_to

Correlation id 關聯標識

一個客戶端可能會發送多個請求給服務器,當服務器處理完後,客戶端沒法辨別在回調隊列中的響應具體和那個請求時對應的。爲了處理這種狀況,客戶端在發送每一個請求時,同時會附帶一個獨有correlation_id屬性,這樣客戶端在回調隊列中根據correlation_id字段的值就能夠分辨此響應屬於哪一個請求。

 
客戶端發送請求:某個應用將請求信息交給客戶端,而後客戶端發送RPC請求,在發送RPC請求到RPC請求隊列時,客戶端至少發送帶有reply_to以及correlation_id兩個屬性的信息

服務器端工做流: 等待接受客戶端發來RPC請求,當請求出現的時候,服務器從RPC請求隊列中取出請求,而後處理後,將響應發送到reply_to指定的回調隊列中

客戶端接受處理結果: 客戶端等待回調隊列中出現響應,當響應出現時,它會根據響應中correlation_id字段的值,將其返回給對應的應用

服務器端

# !/usr/bin/env python
import pika

# 創建鏈接,服務器地址爲localhost,可指定ip地址
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))

# 創建會話
channel = connection.channel()

# 聲明RPC請求隊列
channel.queue_declare(queue='rpc_queue')


# 數據處理方法
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)


# 對RPC請求隊列中的請求進行處理
def on_request(ch, method, props, body):
n = int(body)

print(" [.] fib(%s)" % n)

# 調用數據處理方法
response = fib(n)

# 將處理結果(響應)發送到回調隊列
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id= \
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag)


# 負載均衡,同一時刻發送給該服務器的請求不超過一個
channel.basic_qos(prefetch_count=1)

# 服務器訂閱RPC請求隊列,當隊列中有請求時,將調用`on_request`方法處理請求
channel.basic_consume(on_request, queue='rpc_queue') # 拿到客戶端發送過來的數據,而後執行on_request方法

print(" [x] Awaiting RPC requests")
channel.start_consuming()

客戶端

 
    
# !/usr/bin/env python
import pika
import uuid


class FibonacciRpcClient(object):
def __init__(self):
"""
客戶端啓動時,建立回調隊列,會開啓會話用於發送RPC請求以及接受響應

"""
# 創建鏈接,指定服務器的ip地址,鏈接到rabbitmq服務器
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
# 創建一個會話,每一個channel表明一個會話任務
self.channel = self.connection.channel()
# 聲明回調隊列,再次聲明的緣由是,服務器和客戶端可能前後開啓,該聲明是冪等的,屢次聲明,但只生效一次
result = self.channel.queue_declare(exclusive=True)
# 將次隊列指定爲當前客戶端的回調隊列
self.callback_queue = result.method.queue # 注意理解=後面代碼的意思,隨機建立名字

# 客戶端訂閱回調隊列,當回調隊列中有響應時,調用`on_response`方法對響應進行處理;
self.channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue) # 定義客戶端消費回調隊列時的方法

# 對回調隊列中的響應進行處理的函數
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = body

# 發出RPC請求
def call(self, n):
# 初始化 response
self.response = None
# 生成correlation_id
self.corr_id = str(uuid.uuid4()) # 給發送的數據進行標記,當不一樣的數據發送時,返回的值必須知曉是哪一個數據的結果
# 發送RPC請求內容到RPC請求隊列`rpc_queue`,同時發送的還有`reply_to`和`correlation_id`
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to=self.callback_queue, # 聲明對方發送的數據是發送到哪一個隊列中
correlation_id=self.corr_id, # 數據標記字符串
),
body=str(n)) # 將數據發送到rpc_queue中

while self.response is None: # 斷定response是否有值,沒有值的話一直在這while循環
self.connection.process_data_events() # basic_consume和他有關
return int(self.response)


# 創建客戶端
fibonacci_rpc = FibonacciRpcClient() # 第一步建立對象執行init方法

# 發送RPC請求
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30) # 第二步執行call方法
print(" [.] Got %r" % response)
 

 

 

sudo rabbitmqctl add_user alex 123
# 設置用戶爲administrator角色
sudo rabbitmqctl set_user_tags alex administrator
# 設置權限
sudo rabbitmqctl set_permissions -p "/" alex '.''.''.'

# 而後重啓rabbiMQ服務
sudo /etc/init.d/rabbitmq-server restart
 
# 而後可使用剛纔的用戶遠程鏈接rabbitmq server了。


------------------------------
credentials = pika.PlainCredentials("alex","123")

connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.14.47',credentials=credentials))
相關文章
相關標籤/搜索