mq 的topic 模式,就是根据通配符去匹配路由,决定发送到那个队列。
通配符的使用
*表示一个单词,# 表示匹配零个或多个单词
代码如下:
produce
import pika
from pika.exchange_type import ExchangeType
con = pika.BlockingConnection(
pika.ConnectionParameters(host="localhost")
)
channel = con.channel()
channel.exchange_declare(exchange="topic_logs",exchange_type=ExchangeType.topic)
message = "have a good time !"
# 声明队列
result = channel.queue_declare(queue='good_02')
queue_name = result.method.queue
result = channel.queue_declare(queue='good_01')
queue_name_01 = result.method.queue
# 绑定队列 # 其实队列名可以直接写 good_02
channel.queue_bind(queue_name,exchange="topic_logs",routing_key="*.good") # * 匹配一个单词
channel.queue_bind(queue_name_01,exchange="topic_logs",routing_key="#.good") # # 匹配0个或者多个单词
# 发送消息 此时会给 good_02和 good_01 都发送消息。
channel.basic_publish(exchange="topic_logs",routing_key="task.good",body= message)
con.close()
consumer
import pika
from pika.exchange_type import ExchangeType
# 创建连接对象
con = pika.BlockingConnection(
pika.ConnectionParameters(host="localhost")
)
# 建立通道
channel = con.channel()
# 声明交换机类型
channel.exchange_declare(exchange="topic_logs", exchange_type=ExchangeType.topic)
# 消费good_01 中的任务
result = channel.queue_declare('good_01')
queue_name = result.method.queue
def callback(ch, method, properties, body):
print(
"%s : %s" % (method.routing_key, body)
)
try:
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True
)
channel.start_consuming()
except KeyboardInterrupt:
exit(0)



