RabbitMQ (Fri)--Topics
' Topic Exchange ' in ' RABBITMQ ' matches the routing key with a pattern, which is similar to a regular match to receive the information you like.
Topic Exchange
If you want to use ' topic ' mode, then you can set ' Routing_key '. Instead, the value needs to be set according to certain requirements.
' Routing_key ' in topic mode, you should select a group of words that have a specific attribute as the value.
- \* (Star) can substitute for exactly one word.
- # (hash) can substitute for zero or more words.
For example, if the producer's ' Routing_key ' is set to ' Test1.test2.test3 ', then the ' routing_key ' that is consumed in the binding message queue must match the producer's ' Routing_key '.
#producersRouting_key ='Test1.test2.test3'channel.basic_publish (Exchange='topic_test', Routing_key=routing_key, body=message)#ConsumerRouting_key ='test1.*' #can beRouting_key ='*.test2.*' #can beRouting_key ='test3' #not toChannel.queue_bind (exchange='Topic_logs', Queue=queue_name, Routing_key=binding_key)
Example
Producers as follows, will be set to ' Routing_key ' for A and B, then need to set two consumers ' Routing_key ' to read the message separately.
#!/usr/bin/env python#Coding=utf-8ImportPikaImportSYSImporttimeconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.exchange_declare (Exchange='topic_test', type='Topic') Message="Test" forIinchRange (20): forIteminch['A','B']: Routing_key=Item channel.basic_publish (Exchange='topic_test', Routing_key=routing_key, body=message+Item)Print "[x] Sent%r:%r"%(routing_key, message) Time.sleep (2) Connection.close ()
The consumers are as follows, and the start commands are:
Python receive.py Apython receive.py B
Consumers are as follows:
#!/usr/bin/env python#Coding=utf-8ImportPikaImportSYSdefCallback (ch, method, properties, body):Print "[x]%r:%r"%(Method.routing_key, body,) connection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.exchange_declare (Exchange='topic_test', type='Topic') Result= Channel.queue_declare (exclusive=True) queue_name=Result.method.queuebinding_key= Sys.argv[1]Print "Usage:%s [Binding_key] ..."% (sys.argv[1]) channel.queue_bind (Exchange='topic_test', Queue=queue_name, routing_key=Binding_key)Print '[*] waiting for logs. To exit Press CTRL + C'Channel.basic_consume (callback, queue=queue_name, no_ack=True) channel.start_consuming ()
RabbitMQ (Fri)--Topics