【rabbitmq-Python】-發佈Publish 與訂閱Subscribe


發佈/訂閱,使用扇型交換機(fanout)

https://pika.readthedocs.io/en/stable/
pip install pika

發佈端(Publish)

# coding=utf8
'''
發佈/訂閱
Publish
https://github.com/rabbitmq/rabbitmq-tutorials
https://www.rabbitmq.com/tutorials/tutorial-three-python.html
'''
import pika
import sys

# 認證信息, rabbitmq 的賬號密碼
credentials = pika.PlainCredentials('admin', 'admin')

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.0.83', credentials=credentials))
# 創建
channel = connection.channel()
# 創建一個fanout類型的交換機,命名爲logs
# 扇型交換機(fanout exchange),它把消息發送給它所知道的所有隊列
channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = '_'.join(sys.argv[1:]) or 'hello publish!'
channel.basic_publish(exchange='logs', routing_key='', body=message)
# 關閉連接
connection.close()

訂閱端(Subscribe)

# coding=utf8
'''
發佈/訂閱
Subscribe
https://github.com/rabbitmq/rabbitmq-tutorials
https://www.rabbitmq.com/tutorials/tutorial-three-python.html
'''
import pika

# 認證信息, rabbitmq 的賬號密碼
credentials = pika.PlainCredentials('admin', 'admin')

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.0.83', credentials=credentials))

channel = connection.channel()
# 創建一個fanout類型的交換機,命名爲logs
# 扇型交換機(fanout exchange),它把消息發送給它所知道的所有隊列
channel.exchange_declare(exchange='logs', exchange_type='fanout')

# 定義臨時隊列
# 當與消費者(consumer)斷開連接的時候,這個隊列被立即刪除
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
# 綁定隊列到扇形交換機logs
# 交換機將會把消息添加到我們的隊列中
channel.queue_bind(exchange='logs', queue=queue_name)

def callback(ch, method, properties, body):
	‘’‘
	訂閱回調函數
	‘’‘
    print('subscribe:{}'.format(body))

# 消費隊列
channel.basic_consume(
    queue=queue_name,
    on_message_callback=callback,
    auto_ack=True
)
channel.start_consuming()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章