Python 消息队列rabbitmq使用之 更加细致的 有选择的 发布消息/接收消息-头交换机topic

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haeasringnar/article/details/82716335

1、发布端代码

# new_topic_p.py
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# 指定使用头交换机
channel.exchange_declare(exchange='topic_logs',exchange_type='topic')

# 获取运行脚本时的输入 
routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
# 获取要传入类型的消息
message = ' '.join(sys.argv[2:]) or 'Hello World!'
# 发布消息
channel.basic_publish(exchange='topic_logs',
                      routing_key=routing_key,
                      body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()

2、消费端代码

# new_topic_c.py
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='topic_logs',exchange_type='topic')

result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

# 获取要绑定的key
binding_keys = sys.argv[1:]
if not binding_keys:
    sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    sys.exit(1)

# 循环绑定key,可以绑定多个
for binding_key in binding_keys:
    channel.queue_bind(exchange='topic_logs',
                       queue=queue_name,
                       routing_key=binding_key)

print(' [*] Waiting for logs. To exit press CTRL+C')

def callback(ch, method, properties, body):
    print(" [x] %r:%r" % (method.routing_key, body))

channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()

3、如何运行
消费端:
执行下边命令 接收所有日志:

python new_topic_c.py "#"

执行下边命令 接收来自”kern“设备的日志:

python new_topic_c.py "kern.*"

执行下边命令 只接收严重程度为”critical“的日志:

python new_topic_c.py "*.critical"

执行下边命令 建立多个绑定:

python new_topic_c.py "kern.*" "*.critical"

发布端:

python new_topic_p.py "kern.critical" "A critical kernel error"
展开阅读全文

没有更多推荐了,返回首页