上一篇博文我们队exchange的direct type进行了测试,但是用户的需求总是在变化,上述在对消息进行路由的时候
通过message的basic_publish routing_key参数是否匹配queue_bind的routing_key来决定消息到deliver到
那一个queue。
但是当用户的两个key不能够完全枚举的时候我们该怎么办呢,
dev1_info
dev2_info
...
dev1_warning
dev2_warning
...
dev1_error
dev1_error
...
这时候,通过直接bind,
看起来就不在可行?那该怎么办?这时候topic就要隆重出场了
exchange是通过支持模式来实现功能增强的。其中
* (star) can substitute for exactly one word.
# (hash) can substitute for zero or more words.
这样在bind的时候我们可以有更多的选择
如下的消息模式".."
Q1 is bound with binding key "*.orange.*"
and Q2 with "*.*.rabbit"
Q1 is interested in all the orange animals.
Q2 wants to hear everything about rabbits, and everything about lazy animals.
- #!/usr/bin/env python
- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='topic_logs',
- type='topic')
- 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 " [x] Sent %r:%r" % (routing_key, message)
- connection.close()
- #!/usr/bin/env python
- import pika
- import sys
- connection = pika.BlockingConnection(pika.ConnectionParameters(
- host='localhost'))
- channel = connection.channel()
- channel.exchange_declare(exchange='topic_logs',
- type='topic')
- result = channel.queue_declare(exclusive=True)
- queue_name = result.method.queue
- binding_keys = sys.argv[1:]
- if not binding_keys:
- print >> sys.stderr, "Usage: %s [binding_key]..." % (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 ' [*] Waiting for logs. To exit press CTRL+C'
- def callback(ch, method, properties, body):
- print " [x] %r:%r" % (method.routing_key, body,)
- channel.basic_consume(callback,
- queue=queue_name,
- no_ack=True)
- channel.start_consuming()
CONSOLE 1
H:\mq>topic_send.py "kern.critical" "A critical kernel error"
[x] Sent 'kern.critical':'A critical kernel error'
CONSOLE2
H:\mq>topic_receiver.py "#"
[*] Waiting for logs. To exit press CTRL+C
[x] 'kern.critical':'A critical kernel error'
CONSOLE3
H:\mq>topic_receiver.py "*.critical"
[*] Waiting for logs. To exit press CTRL+C
[x] 'kern.critical':'A critical kernel error'
CONSOLE 4
H:\mq>topic_receiver.py "kern.*"
[*] Waiting for logs. To exit press CTRL+C
[x] 'kern.critical':'A critical kernel error'
可以看到的通过不同的bind方式,我们可以对自己感兴趣的消息进行bind,并rout到不同的message queue。
REF:
阅读(1426) | 评论(0) | 转发(0) |