# subscriber.py
import pika
import json
def start_subscriber():
connection = pika.BlockingConnection(
pika.ConnectionParameters("host", 5672, "/", pika.PlainCredentials("admin", "admin"))
)
channel = connection.channel()
# 声明相同的 fanout exchange
channel.exchange_declare(exchange='pubsub_exchange', exchange_type='fanout', durable=True)
# 创建临时队列(exclusive=True 表示连接断开后自动删除)
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
# 绑定队列到 exchange
channel.queue_bind(exchange='pubsub_exchange', queue=queue_name)
def callback(ch, method, properties, body):
print(f"Received: {json.loads(body)}")
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
print('Waiting for messages...')
channel.start_consuming()
if __name__ == "__main__":
start_subscriber()