python rabbitmq(四) 发布订阅之"topic"

# 3topic实现模糊匹配发布消息
#       direct实现了根据自定义的routing_key来标示不同的queue,使用topic可以让队列绑定几个模糊的关键字,
#       之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列
#       # 表示可以匹配 0 个 或 多个 单词
#       *  表示只能匹配 一个 单词

mq_topic_producer.py

import pika

# 3topic实现模糊匹配发布消息
#       direct实现了根据自定义的routing_key来标示不同的queue,使用topic可以让队列绑定几个模糊的关键字,
#       之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列
#       # 表示可以匹配 0 个 或 多个 单词
#       *  表示只能匹配 一个 单词
# 如:
# 单词之间必须用"."隔开
# like.you 和like.you.you
# like.# 会匹配到 like.you 和 like.you.you
# like.* 只会匹配到like.you


credient = pika.PlainCredentials(username='admin',password='admin')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='0.0.0.0',port=5672,virtual_host='/',credentials=credient))

channel = connection.channel()

channel.exchange_declare(exchange='topic_exchange',exchange_type='topic',durable=True)

for i in range(10):
    message = f'time {i}'
    if i % 2 == 0:
        channel.basic_publish(exchange='topic_exchange',routing_key='like.you',body=message)
    else:
        channel.basic_publish(exchange='topic_exchange', routing_key='hate.you', body=message)
    print(message)
connection.close()

mq_topic_consumer1.py

import pika


credient = pika.PlainCredentials(username='admin',password='admin')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='0.0.0.0',port=5672,virtual_host='/',credentials=credient))

channel = connection.channel()
channel.exchange_declare(exchange='topic_exchange',exchange_type='topic',durable=True)
channel.queue_declare(queue='topic_queue1',durable=True,auto_delete=True)

channel.queue_bind(exchange='topic_exchange',queue='topic_queue1',routing_key='like.#') # routing_ke队列指定以什么规则绑定交换和队列

def callback(channel,method,properity,body):
    channel.basic_ack(delivery_tag=method.delivery_tag)
    print(body.decode())

channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_message_callback=callback,queue='topic_queue1')
channel.start_consuming()

mq_topic_consumer2.py

import pika


credient = pika.PlainCredentials(username='admin',password='admin')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='0.0.0.0',port=5672,virtual_host='/',credentials=credient))

channel = connection.channel()
channel.exchange_declare(exchange='topic_exchange',exchange_type='topic',durable=True)
channel.queue_declare(queue='topic_queue2',durable=True,auto_delete=True)
channel.queue_bind(exchange='topic_exchange',queue='topic_queue2',routing_key='hate.#') # routing_ke队列指定以什么规则绑定交换和队列

def callback(channel,method,properity,body):
    channel.basic_ack(delivery_tag=method.delivery_tag)
    print(body.decode())

channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_message_callback=callback,queue='topic_queue2')
channel.start_consuming()

你可能感兴趣的:(python,rabbitmq)