hmjrun / hmj

my Note
1 stars 1 forks source link

AMPQ 学习笔记 #10

Open hmjrun opened 7 years ago

hmjrun commented 7 years ago

AMPQ (with python)

RabbitMQ is a message broker: it accepts and forwards messages. You can think about it as a post office: when you put the mail that you want posting in a post box, you can be sure that Mr. Postman will eventually deliver the mail to your recipient. In this analogy, RabbitMQ is a post box, a post office and a postman.

the flowing is some notes about study ampq by python :)

hmjrun commented 7 years ago

hello world

P(producer) sends messages to the "hello" queue. The C(consumer) receives messages from that queue. x

send.py

import pika
# http://rabbitmq.mr-ping.com/tutorials_with_python/[1]Hello_World.html
# https://www.rabbitmq.com/tutorials/tutorial-one-python.html

# 1. establish a connection with RabbitMQ server.
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# 2. create a queue named 'hello'
channel.queue_declare(queue='hello')

# 3. In RabbitMQ a message can never be sent directly to the queue, 
#    it always needs to go through an exchange. 
#    But let's not get dragged down by the details 
#    ‒ you can read more about exchanges in the third part of this tutorial. 
#    (https://www.rabbitmq.com/tutorials/tutorial-three-python.html)
#    All we need to know now is how to use a default exchange identified by an empty string. 
#    This exchange is special ‒ it allows us to specify exactly to which queue the message should go. 
#    The queue name needs to be specified in the routing_key parameter:
channel.basic_publish(exchange='', routing_key='hello', body='Hello Word!')
print ("[huangmj] Sernt 'Hello World!'")

# 4. closing the connection.
connection.close()

receive.py

# Pika, which is the Python client recommended by the RabbitMQ team.
import pika

# 1. connect to RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# 2. to make sure that the queue exists. Creating a queue.
#    ‒ we can run the command(queue_declare) as many times as we like, and only one will be created.
channel.queue_declare(queue='hello')
print ("Waiting for messages. To exit press CTRL + C")

# 3. Whenever we receive a message, 
#    this callback function is called by the Pika library
def callback(ch,method,properties, body):
    print ("[huanngmj Received {}".format(body))

# 4. tell RabbitMQ that this particular callback function 
#    should receive messages from our hello queue:
channel.basic_consume(callback, queue='hello', no_ack=True)

# 5. enter a never-ending loop that waits for data and runs callbacks whenever necessary.
channel.start_consuming()