可视化模拟RabbitMQ心脏-Exchange三种类型消息分发流程
import pika
import time
# 连接到RabbitMQ服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明exchange、queue和binding
exchange_type = 'direct' # 这里选择直接类型
exchange_name = 'test_exchange_direct'
queue_name = 'test_queue_direct'
routing_key = 'test_direct'
channel.exchange_declare(exchange=exchange_name, exchange_type=exchange_type)
channel.queue_declare(queue=queue_name)
channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=routing_key)
print(f" [*] Waiting for messages. To exit press CTRL+C")
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
# 开始监听队列,并设置回调函数
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
# 开始循环以便于监听消息
channel.start_consuming()
这段代码演示了如何声明一个直接类型的Exchange,创建一个队列并将它绑定到这个Exchange上,然后开始监听这个队列的消息。当有消息到达时,会调用回调函数callback
来处理接收到的消息。这是RabbitMQ消息分发的基本流程,适用于直接类型的Exchange。
评论已关闭