1. 程式人生 > 實用技巧 >direct直連交換機實現訂閱訊息的子集

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"

訂閱日誌

worker1python 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 都能收到