# -*- coding: utf-8 -*- import pika import sys user_info = pika.PlainCredentials('user', 'Un2yzriWm7veSDoh') connection = pika.BlockingConnection( pika.ConnectionParameters('rabbitmq.rabbitmq.svc.cluster.local', 5672, '/', user_info) ) channel = connection.channel() # 1. 声明同一个 topic 交换机 channel.exchange_declare(exchange='topic_logs', exchange_type='topic') # 2. 创建临时队列 result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue # 3. 从命令行读取要监听的 pattern(可多个) binding_keys = sys.argv[1:] if not binding_keys: sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0]) sys.exit(1) for binding_key in binding_keys: channel.queue_bind(exchange='topic_logs', queue=queue_name, routing_key=binding_key) print(f" [*] Queue bound with pattern: {binding_key}") print(' [*] Waiting for logs. To exit press CTRL+C') # 4. 回调 def callback(ch, method, properties, body): print(f" [x] {method.routing_key}:{body.decode()}") channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()