Then the previous chapter uses exchange_type= ' Direct ' for message delivery. The message is then fully matched and sent to the corresponding receiving end. Now we want to do one thing:
C1 gets the message containing the orange content, and the message is made up of 3 words.
C2 gets a message that contains: Rabbit content, and is also a 3-word composition, and contains a message with the beginning of the lazy message, which is the length >2
In the,
Quick.orange.rabbit:Q1 Q2 will receive
Lazy.orange.elephant:Q1 Q2 will receive
Quick.orange.fox: only to Q1
Lazy.brown.fox: only to Q2
Lazy.pink.rabbit: only to Q2
Quick.orange.male.rabbit: I can't go anywhere.
Lazy.orange.male.rabbit: only to Q2
In the message
*: Represents a single word
#: Represents n words
So, how do we do that?
Send side:
Import Pika
Import Sys
Connection = Pika. Blockingconnection (Pika. Connectionparameters (host= ' localhost '))
Channel = Connection.channel ()
#创建交换机和上一章一样. Just the type changed to: exchange_type= ' topic '
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 ()
Receiving end:
Import Pika
Import Sys
Connection = Pika. Blockingconnection (Pika. Connectionparameters (
host= ' localhost '))
Channel = Connection.channel ()
#和发送端保持一致 Note: exchange_type= ' topic '
Channel.exchange_declare (exchange= ' topic_logs ',
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 (Callback,
Queue=queue_name,
No_ack=true)
Channel.start_consuming ()
Note: There is a particularly strange problem here today. Is that the receiving end program executes to:
result = Channel.queue_declare (exclusive=true)
Into a dead loop. What should I do now?
Restart the RABBITMQ service. This series of articles RABBITMQ used: 3.6.12.
Next, we'll discuss using RABBITMQ to implement RPC
I hope the cow can keep up with the pace
Python Operations RABBITMQ Series (v): Assigning messages based on topics