RabbitMQ-1介紹

一. RabbitMQ-1

什麼叫消息隊列

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

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

爲什麼使用消息隊列

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

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

RabbitMQ介紹

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

二. rabbitMQ安裝

2.1 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

2.2 Mac

# brew install rabbitmq
# export PATH=$PATH:/usr/local/sbin
# rabbitmq-server

2.2 rabbitMQ工做模型

2.2.1 簡單模式

示例函數

# ######################### 生產者 #########################
#!/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)

# 須要producer確認以後在刪除消息內容的時候須要將no_ack置爲False 
channel.basic_consume( callback,
                       queue='hello',
                       no_ack=True)

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

相關參數說明

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

  • 回調函數中的ch.basic_ack(delivery_tag=method.delivery_tag)
  • basic_comsume中的no_ack=False
  1. 消息接收端應該這麼寫
    import pika

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

channel.queue_declare(queue='hello')ui

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:消息不丟失

生產者

#!/usr/bin/env python
import pika

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

make message persistent

channel.queue_declare(queue='hello', durable=True)

channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print(" [x] Sent 'Hello World!'")
connection.close()

消費者

#!/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', durable=True)

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()

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 發佈訂閱

![模型圖](https://img-blog.csdnimg.cn/20201107170240838.png)

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

生產者

#!/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')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',
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)
queue_name = result.method.queue

channel.queue_bind(exchange='logs',
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 關鍵字發送

![模型圖](https://img-blog.csdnimg.cn/20201107170350176.png)

以前示例,發送消息時明確指定某個隊列並向其中發送消息,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',
exchange_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()

### 3.3 模糊匹配

![模型圖](https://img-blog.csdnimg.cn/20201107170430114.png)

|  發送者路由值    |    隊列中  |
| --- | --- |
|  www.weshuke.python    | old.*  -- 不匹配  |
|  age.weshuke.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',
exchange_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()

##  基於RabbitMQ的RPC

### Callback queue 回調隊列

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

### Correlation id 關聯標識

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

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

2. 服務器端工做流: 等待接受客戶端發來RPC請求,當請求出現的時候,服務器從RPC請求隊列中取出請求,而後處理後,將響應發送到reply_to指定的回調隊列中.
3. 客戶端接受處理結果: 客戶端等待回調隊列中出現響應,當響應出現時,它會根據響應中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)

channel.basic_consume(on_request, queue='rpc_queue')

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

### 客戶端

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

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

「」「

    # 創建鏈接,指定服務器的ip地址
    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))

    while self.response is None:
        self.connection.process_data_events()
    return int(self.response)

創建客戶端

fibonacci_rpc = FibonacciRpcClient()

發送RPC請求

print(" [x] Requesting fib(30)")response = fibonacci_rpc.call(30)print(" [.] Got %r" % response)

相關文章
相關標籤/搜索