【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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章