Topics
In the previous tutorial we improved logging system, however, can only use fanout exchange broadcast, we receive log using direct selection. Even with direct exchange to improve our system, it is still limited and can not be routed based on multiple criteria.
In our system, we not only want to subscribe to the severity of the log, but also on the issue of resources log, you may understand this concept from syslog unix tool, the tool according to the severity (info / warn / crit ... ) and tools (auth / cron / kern ...) routing logs. This will give us a lot of flexibility - we may only want to hear from a serious error "cron" can also listen to all log "kern" of.
- * (Star) can replace a word (word)
(Hash) can replace one or more words (words)
Figure explanation
topic_send.py
# -*- coding: utf-8 -*-
'''
@Time : 19-11-1 下午3:41
@Author : jz
@FileName: topic_send.py
@Software: PyCharm
'''
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',exchange_type='topic')
routing_key = sys.argv[1] if len(sys.argv)>2 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()
topic_receive.py
# -*- coding: utf-8 -*-
'''
@Time : 19-11-1 下午3:41
@Author : jz
@FileName: topic_receive.py
@Software: PyCharm
'''
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_log',exchange_type='topic')
result = channel.queue_declare('',exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage:%s [binding_key]....\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('[*] 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(queue=queue_name,
on_message_callback=callback,auto_ack=True)
channel.start_consuming()