Home >Backend Development >Python Tutorial >Detailed explanation of RabbitMQ operation graphic code in Python
RabbitMQ is a complete, reusable enterprise messaging system based on AMQP.
MQ stands for Message Queue. Message Queuing (MQ) is an application-to-application communication method.
Message queue works using publish-subscribe mode. The message sender is the message source. After processing the message, it sends the message to the distributed message queue. The message receiver obtains the message from the distributed message queue and continues processing. It can be seen that there is no direct coupling between the message sender and the message receiver. The message sender ends processing the message when it sends the message to the distributed message queue, while the message receiver only needs to obtain the message from the distributed message queue. Processing without knowing where the message came from.
Through message queue communication, low coupling between service fingers A and B is maintained to achieve flexible business expansion.
pika is the official Python AMQP library written by the RabbitMQ team.
$ brew install rabbitmq$ usr/local/sbin/rabbitmq-server
Installation pika
pip install pika
# coding: utf-8import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello, World!')print 'send msg: Hello World!'connection.close()
# coding: utf-8import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello')def callback(ch, method, properties, body): print 'receive msg: %s' % body channel.basic_consume(callback, queue='hello', no_ack=False)print 'waiting for msg...'channel.start_consuming()
Running result:
# sender.py 运行2次send msg: Hello World!# receiverwaiting for msg... receive msg: Hello, World! receive msg: Hello, World!
After the consumer processes the message, it does not exit and can still process subsequent messages.
The above is the detailed content of Detailed explanation of RabbitMQ operation graphic code in Python. For more information, please follow other related articles on the PHP Chinese website!