RabbitMQ (c)--Publish/subscribe
' RABBITMQ ' supports a one-to-many pattern, commonly called publish/subscribe. That is, when a producer generates a message, ' RABBITMQ ' will distribute the message to all consumers.
Exchanges
In the previous tutorial, only the basic message model was used:
- Producers generate messages
- To add a message to a message queue
- Consumers receive messages
In the ' RABBITMQ Complete message model ', this is not the case. In fact, the producer does not know whether the message is sent to the queue, but rather sends the message directly to ' exchanges '.
The function of ' exchanges ' is very simple to understand, it is only responsible for receiving the data sent by the producer and adding the data to the message queue. However, in the presence of multiple message queues, ' exchanges ' must know which message queue each message is to be added to.
' RABBITMQ ' offers several ' exchanges ', including: ' Direct ', ' topic ', ' Headers ' and ' fanout '.
Here, just introduce the use of fanout.
Channel.exchange_declare (exchange='news', type='fanout')
Then, publish the message:
Channel.basic_publish (exchange='news', routing_key=', Body=message)
Temporary queues
Given the need to specify the same message queue in the producer and consumer to implement message communication, what if a message queue is not specifically specified?
Then you need to use the default parameters to let the system generate a specific message queue.
result = Channel.queue_declare ()
Bindings
In order to send a message queue for a specified send, you must create a relationship between Exchange and Message Queuing:
Channel.queue_bind (exchange='news', Queue=result.method.queue)
Example
As a producer of publish:
#!/usr/bin/env python#Coding=utf-8ImportPikaImportsysconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.exchange_declare (Exchange='News', type='fanout') forIinchRange (100): Message= str (i) +'Hello world!'channel.basic_publish (Exchange='News', routing_key="', body=message)Print "[x] Sent%r"%(message,)ImportTime Time.sleep (2) Connection.close ()
As a consumer of subscribe:
#!/usr/bin/env python#Coding=utf-8Importpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.exchange_declare (Exchange='News', type='fanout') Result= Channel.queue_declare (exclusive=True) queue_name=Result.method.queuechannel.queue_bind (Exchange='News', Queue=queue_name)Print '[*] waiting for news. To exit Press CTRL + C'defCallback (ch, method, properties, body):Print "[x]%r"%(body,) Channel.basic_consume (callback, queue=queue_name, No_ack=True) channel.start_consuming ()
RabbitMQ (c)--Publish/subscribe