rabbitmq学习笔记-----exchange的topic类型(type=topic)使用主题进行消息分发
上一节我们实现了Consumer可以监听不同severity的log,但是要实现筛选出错误级别下某些特定的模块就没办法实现,比如syslog unix的日志工具,它可以通过severity (info/warn/crit...) 和模块(auth/cron/kern...)。这可能更是我们想要的:我们可以仅仅需要cron模块的log,为了实现类似的功能,我们需要用到topic exchange
- 本节要实现的架构图

- topic exchange
对于Message的routing_key是有限制的,不能使任意的。格式是以点号“."分割的字符表。比如:"stock.usd.nyse", "nyse.vmw", "quick.orange.rabbit"。你可以放任意的key在routing_key中,当然最长不能超过255 bytes
对于routing_key,有两个特殊字符(在正则表达式里叫元字符):
- * (星号) 代表任意 一个单词
- # (hash) 0个或者多个单词
- 代码实现
consume.py
from amqplib import client_0_8 as amqp import time import sys ##创建con和chanel con = amqp.Connection(host="192.168.1.188:32769", userid="guest", password="guest", virtual_host="/") chan = con.channel() result = chan.queue_declare(exclusive=True) chan.exchange_declare(exchange='log',type='topic') severities = sys.argv[1:] if not severities: print(sys.stderr, "Usage: %s [info] [warning] [error]" %(sys.argv[0],)) exit() for serve in severities: chan.queue_bind(queue=result[0],exchange='log',routing_key=serve) def recv_callback(msg): print('屏幕打印消息:' + msg.body + '它来自'+ str(msg.channel.channel_id)) chan.basic_consume(queue=result[0],callback=recv_callback,no_ack=True) while True: chan.wait() chan.close() con.close()
product.py
from amqplib import client_0_8 as amqp import sys ##创建con和chanel con = amqp.Connection(host="192.168.1.188:32769", userid="guest", password="guest", virtual_host="/") chan = con.channel() chan.exchange_declare(exchange='log', type='topic') severity = sys.argv[1] if len(sys.argv) > 1 else 'info' massage = ' '.join(sys.argv[2:]) or 'Hello World!' msg = amqp.Message(massage) chan.basic_publish(msg,exchange='log',routing_key=severity) chan.close() con.close()
- 实验
开启四个consume
consume(1) 运行 python cosume.py "#"

consume(2) 运行 python cosume.py "error.*"

consume(3) 运行 python cosume.py "*.rcj"

consume(4) 运行 python cosume.py "error.*" "*.rcj"

分别执行下面的product
(1)python product.py "error.rcj" "这次是测试type=topic的时刻,其中报错级别为error.rcj"
(2)python product.py "error.ljj" "这次是测试type=topic的时刻,其中报错级别为error.ljj"
(3)python product.py "warning.ljj" "这次是测试type=topic的时刻,其中报错级别为warning.ljj"
(4)python product.py "warning.rcj" "这次是测试type=topic的时刻,其中报错级别为warning.rcj"
(5)>python product.py "ljj*8*" "这次是测试type=topic的时 刻,其中报错级别为ljj*8*"
最终得到上述四个端口的结果
从结果可以看出实现了消息结果模块分类。

浙公网安备 33010602011771号