direct直连交换机实现订阅消息的子集

参考链接 

英文:  https://www.rabbitmq.com/tutorials/tutorial-four-python.html

中文: https://rabbitmq.mr-ping.com/tutorials_with_python/[4]Routing.html

提交日志 sendlog.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='direct_logs', exchange_type='direct')

severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(
    exchange='direct_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='direct_logs', exchange_type='direct')

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

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

for severity in severities:
    channel.queue_bind(
        exchange='direct_logs', queue=queue_name, routing_key=severity)

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()

 

发布日志

python sendlog.py error  "helllo223"

python sendlog.py info "hellloinfowarn"

python sendlog.py  warn "hellloinfowarn"

订阅日志

worker1  python sub.py  info  warn

worker2   python sub.py error warn

备注: 两个worker 的队列都绑定了 warn 绑定键   多个队列使用相同的绑定键是合法的

It is perfectly legal to bind multiple queues with the same binding key

 

效果:  发布的 info 信息 只有 worker1 能收到  

              发布的 error信息只有worker2 能收到

            发布的 warn信息 worker1 worker2 都能收到

 

posted on 2020-10-09 17:52  思此狂  阅读(101)  评论(0编辑  收藏  举报

导航