RabbitMQ广播:topic模式

topic模式跟direct差不多,只是把type改一下就行。

direct是把固定的routing_key跟queue绑定,topic是把模糊的routing_key跟queue绑定

原理图:

发布者:

'''
发布者publisher
'''
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
                         type='topic')  # 1、改成type='topic'
# 2、改默认格式为*.info
routing_key = sys.argv[1] if len(sys.argv) > 1 else "anonymous.info"

message = ' '.join(sys.argv[2:]) or " Hello World!"
channel.basic_publish(exchange='topic_logs',
                      routing_key=routing_key,
                      body=message)
print("send :", message)
connection.close()

订阅者:

'''
订阅者subscriber
'''
import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
                         type='topic')  # 3、改topic的类型
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue

# 4、改为binding_keys 就变量名称改了
binding_keys = sys.argv[1]
if not binding_keys:
    sys.stderr.write("Usage: %s [info] [warning] [error]\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("Wait for logs...")
def callback(ch, method, properties, body):
    print("received:", method.routing_key, body)
channel.basic_consume(callback,
                      queue=queue_name,
                      no_ack=True)
channel.start_consuming()

注:  如果需要接收所有格式的消息要用“#”而不是“*”号

猜你喜欢

转载自www.cnblogs.com/staff/p/9932933.html