再一次把RabbitMQ的架構圖拿到這里來:
image.png
其主體分為三個大分部:
- RabbitMQ Server:它是一種傳輸服務,用于維護數據從生產者到消費者間的路線,保證數據能按指定方式進行傳輸。其內包括了交換機和隊列,交換機分發(fā)生產者的數據到指定的隊列,隊列存放生產者發(fā)送的數據。
- Client A,B:生產者,產生數據
- Client 1,2,3:消費者,數據的接收方。
一個簡單的RabbitMQ編程實例
生產者代碼實現步驟:
- 獲得與RabbitMQ Server的連接對象
- 通過連接對象獲得Channel對象,Channel提供了與RabbitMQ交互的操作
- 連接用戶儲存消息數據的隊列,不存在則創(chuàng)建隊列
- 發(fā)送消息到指定的RabbitMQ隊列中
- 關閉RabbitMQ代理的連接
只需按照上面步驟進行編寫代碼即可
import pika
class RabbitMQ(object):
def __init__(self, host, port, username, password, vhost):
self._host = host # broker IP
self._port = port # broker port
self._vhost = vhost # vhost
self._credentials = pika.PlainCredentials(username, password)
self._connection = None
def connect(self):
# 連接RabbitMQ的參數對象
parameter = pika.ConnectionParameters(self._host, self._port, self._vhost,
self._credentials, heartbeat_interval=10)
self._connection = pika.BlockingConnection(parameter) # 建立連接
def put(self, message_str, queue_name, route_key, exchange=''):
if self._connection is None:
return
channel = self._connection.channel() # 獲取channel
channel.queue_declare(queue=queue_name) # 申明使用的queue
# 調用basic_publish方法向RabbitMQ發(fā)送數據, 這個方法應該只支持str類型的數據
channel.basic_publish(
exchange=exchange, # 指定exchange
routing_key=route_key, # 指定路由
body=message_str # 具體發(fā)送的數據
)
def getting_start(self, queue_name):
if self._connection is None:
return
channel = self._connection.channel()
channel.queue_declare(queue=queue_name)
# 調用basic_consume方法,可以傳入一個回調函數
channel.basic_consume(self.callback,
queue=queue_name,
no_ack=True)
channel.start_consuming() # 相當于run_forever(), 當Queue中沒有數據,則一直阻塞等待
@staticmethod
def callback(ch, method, properties, message_str):
"""定義一個回調函數"""
print "[x] Received {0}".format(message_str)
def close(self):
"""關閉RabbitMQ的連接"""
if self._connection is not None:
self._connection.close()