topic型交换机实现灵活路由键的组合分发

[root@jinkang-e2elog rabbitmq]# cat topic-send.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pika
import sys

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

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

severity = sys.argv[1] if len(sys.argv) > 1 else 'vm.centos'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(
    exchange='topic_logs', routing_key=severity, body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
#!/usr/bin/env python
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(queue='', exclusive=True)
queue_name = result.method.queue

bonding_keys = sys.argv[1:]
if not bonding_keys:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for bonding_key in bonding_keys:
    channel.queue_bind(
        exchange='topic_logs', queue=queue_name, routing_key=bonding_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(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

以上demo 实现一个  环境类型.OS类型的 信息的发送分发

 python   topic-send.py  ph.debian

 python   topic-send.py  vm.debian

 python   topic-send.py  ph.centos

 

实现虚拟机/物理机  不同OS 的信息的发送分发。

python  topic-rec.py "ph.*"

python topic-rec.py  "vm.*"

python topic-rec.py  "#"

*  星号用来表示任务一个单词

#  井号用来表示数量的单词(0个或无数个)

 

使用topic 型交换机 可以实现复灵活的 信息的分发实现

posted on 2020-10-09 18:55  思此狂  阅读(193)  评论(0编辑  收藏  举报

导航