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

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

 

posted on 2018-11-09 01:19 要一直走下去 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/staff/p/9932933.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值