日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

消息队列之RabbitMQ

發布時間:2024/9/5 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 消息队列之RabbitMQ 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

知識預覽

  • RabbitMQ
回到頂部

RabbitMQ

什么叫消息隊列

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

消息隊列(Message Queue)是一種應用間的通信方式,消息發送后可以立即返回,由消息系統來確保消息的可靠傳遞。消息發布者只管把消息發布到 MQ 中而不用管誰來取,消息使用者只管從 MQ 中取消息而不管是誰發布的。這樣發布者和使用者都不用知道對方的存在。

為何用消息隊列

從上面的描述中可以看出消息隊列是一種應用間的異步協作機制,那什么時候需要使用 MQ 呢?

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

RabbitMQ?

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

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

中文文檔

rabbitMQ安裝

 forLinux: 復制代碼 安裝配置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會重新將該任務添加到隊列中。

  • 回調函數中的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 timetime.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='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 pikaconnection = 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 timetime.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 sysconnection = 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 pikaconnection = 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() View Code

?3.2 關鍵字發送

exchange type = direct

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

#!/usr/bin/env python import pika import sysconnection = 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.queueseverities = 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 sysconnection = 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 sysconnection = 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.queuebinding_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 sysconnection = 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))

?

轉載于:https://www.cnblogs.com/buyisan/p/8510970.html

總結

以上是生活随笔為你收集整理的消息队列之RabbitMQ的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。