什么是消息隊列
消息(Message)是指在應用間傳送的數據。消息可以非常簡單,比如只包含文本字符串,也可以更復雜,可能包含嵌入對象。
消息隊列(Message Queue)是一種應用間的通信方式,消息發(fā)送后可以立即返回,由消息系統(tǒng)來確保消息的可靠傳遞。消息發(fā)布者只管把消息發(fā)布到 MQ 中而不用管誰來取,消息使用者只管從 MQ 中取消息而不管是誰發(fā)布的。這樣發(fā)布者和使用者都不用知道對方的存在。
為何使用消息隊列
從上面的描述中可以看出消息隊列是一種應用間的異步協(xié)作機制,那什么時候需要使用 MQ 呢?
以常見的訂單系統(tǒng)為例,用戶點擊【下單】按鈕之后的業(yè)務邏輯可能包括:扣減庫存、生成相應單據、發(fā)紅包、發(fā)短信通知。在業(yè)務發(fā)展初期這些邏輯可能放在一起同步執(zhí)行,隨著業(yè)務的發(fā)展訂單量增長,需要提升系統(tǒng)服務的性能,這時可以將一些不需要立即生效的操作拆分出來異步執(zhí)行,比如發(fā)放紅包、發(fā)短信通知等。這種場景下就可以用 MQ ,在下單的主流程(比如扣減庫存、生成相應單據)完成之后發(fā)送一條消息到 MQ 讓主流程快速完結,而由另外的單獨線程拉取MQ的消息(或者由 MQ 推送消息),當發(fā)現 MQ 中有發(fā)紅包或發(fā)短信之類的消息時,執(zhí)行相應的業(yè)務邏輯。
rabbitMQ
RabbitMQ 是一個由 Erlang 語言開發(fā)的 AMQP 的開源實現。
rabbitMQ是一款基于AMQP協(xié)議的消息中間件,它能夠在應用之間提供可靠的消息傳輸。在易用性,擴展性,高可用性上表現優(yōu)秀。使用消息中間件利于應用之間的解耦,生產者(客戶端)無需知道消費者(服務端)的存在。而且兩端可以使用不同的語言編寫,大大提供了靈活性。
rabbitMQ安裝
安裝配置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
查看進程
netstat -lnpt|grep beam
rabbitMQ工作原理
簡單示例
生產者
import pika
# 封裝了socket對象(bind,listen)
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
# 創(chuàng)建通道對象
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() # 關閉鏈接
消費者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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=False)
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會重新將該任務添加到隊列中。
- 回調函數中的
channel.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'
channel.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:消息不丟失
生產者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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()
消費者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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(5)
print('ok')
channel.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 去隊列中獲取 奇數 序列的任務,消費者2去隊列中獲取 偶數 序列的任務。
channel.basic_qos(prefetch_count=1)表示誰來誰取,不再按照奇偶數排列。
消費者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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(5)
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模型
發(fā)布訂閱:fanout

發(fā)布訂閱和簡單的消息隊列區(qū)別在于,發(fā)布訂閱會將消息發(fā)送給所有的訂閱者,而消息隊列中的數據被消費一次便消失。所以,RabbitMQ實現發(fā)布和訂閱時,會為每一個訂閱者創(chuàng)建一個隊列,而發(fā)布者發(fā)布消息時,會將消息放置在所有相關隊列中。
exchange_type = fanout
生產者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
message = "info: Hello World!"
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()
消費者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout') # creates an exchange
result = channel.queue_declare(exclusive=True) # Declare queue, create if needed.
queue_name = result.method.queue # 隊列名
channel.queue_bind(exchange='logs', queue=queue_name) # Bind the queue to the specified exchange
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()
關鍵字發(fā)送:direct

exchange_type = direct
routing_key='info'
之前事例,發(fā)送消息時明確指定某個隊列并向其中發(fā)送消息,RabbitMQ還支持根據關鍵字發(fā)送,即:隊列綁定關鍵字,發(fā)送者將數據根據關鍵字發(fā)送到消息exchange,exchange根據 關鍵字 判定應該將數據發(fā)送至指定隊列。
生產者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
message = "hahaha"
channel.basic_publish(exchange='direct_logs',
routing_key='info',
body=message)
print(" [x] Sent %r" % message)
connection.close()
消費者1
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = ['info', 'error', 'warning']
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()
消費者2
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = ['error', ]
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()
模糊匹配:topic

exchange_type = topic
發(fā)送者路由值 隊列中
old.boy.python old.* -- 不匹配
old.boy.python old.# -- 匹配
在topic類型下,可以讓隊列綁定幾個模糊的關鍵字,之后發(fā)送者將數據發(fā)送到exchange,exchange將傳入”路由值“和 ”關鍵字“進行匹配,匹配成功,則將數據發(fā)送到指定隊列。
- # 表示可以匹配 0 個 或 多個 單詞
- * 表示只能匹配 一個 單詞\
生產者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
message = "lalalala"
channel.basic_publish(exchange='topic_logs',
routing_key='lazy.mxt',
body=message)
print(" [x] Sent %r" % message)
connection.close()
消費者1
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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 = ["*.orange.*", ]
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()
消費者2
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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 = ["*.*.rabbit", "lazy.#"]
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 回調隊列
一個客戶端向服務器發(fā)送請求,服務器端處理請求后,將其處理結果保存在一個存儲體中。而客戶端為了獲得處理結果,那么客戶在向服務器發(fā)送請求時,同時發(fā)送一個回調隊列地址reply_to。
Correlation id 關聯標識
一個客戶端可能會發(fā)送多個請求給服務器,當服務器處理完后,客戶端無法辨別在回調隊列中的響應具體和那個請求時對應的。為了處理這種情況,客戶端在發(fā)送每個請求時,同時會附帶一個獨有correlation_id屬性,這樣客戶端在回調隊列中根據correlation_id字段的值就可以分辨此響應屬于哪個請求。
客戶端發(fā)送請求:某個應用將請求信息交給客戶端,然后客戶端發(fā)送RPC請求,在發(fā)送RPC請求到RPC請求隊列時,客戶端至少發(fā)送帶有reply_to以及correlation_id兩個屬性的信息
服務器端工作流: 等待接受客戶端發(fā)來RPC請求,當請求出現的時候,服務器從RPC請求隊列中取出請求,然后處理后,將響應發(fā)送到reply_to指定的回調隊列中
客戶端接受處理結果: 客戶端等待回調隊列中出現響應,當響應出現時,它會根據響應中correlation_id字段的值,將其返回給對應的應用
服務器端
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.74'))
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)
# 將處理結果(響應)發(fā)送到回調隊列
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)
# 負載均衡,同一時刻發(fā)送給該服務器的請求不超過一個
channel.basic_qos(prefetch_count=1)
# 服務器訂閱RPC請求隊列,當隊列中有請求時,將調用`on_request`方法處理請求
channel.basic_consume(on_request, queue='rpc_queue')
print(" [x] Awaiting RPC requests")
channel.start_consuming()
客戶端
import pika
import uuid
class FibonacciRpcClient(object):
def __init__(self):
"""
客戶端啟動時,創(chuàng)建回調隊列,會開啟會話用于發(fā)送RPC請求以及接受響應
"""
# 建立連接,指定服務器的ip地址
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='192.168.20.74'))
# 建立一個會話,每個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
# 發(fā)出RPC請求
def call(self, n):
# 初始化 response
self.response = None
# 生成correlation_id
self.corr_id = str(uuid.uuid4())
# 發(fā)送RPC請求內容到RPC請求隊列`rpc_queue`,同時發(fā)送的還有`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()
# 發(fā)送RPC請求
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)