1. 程式人生 > >RabbitMQ廣播:topic模式

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

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