RabbitMQ Tutorial 1 https://www.rabbitmq.com/tutorials/tutorial-one-python.html It is a translation of. We look forward to pointing out any translation errors.
This tutorial assumes that RabbitMQ is installed and running on the standard port (5672) on the local host. If you want to use a different host, port, or credentials, you need to adjust your connection settings.
If you encounter any issues through this tutorial, you can contact us through the mailing list.
RabbitMQ is a message broker. The main idea is very simple: accept and deliver messages. You can think of it as a post office: when you write a letter to a post, you will be confident that the mail carrier will eventually deliver it to the recipient. According to this metaphor, RabbitMQ is a post, a post office, and a mail carrier.
The big difference between RabbitMQ and the post office is the fact that it doesn't handle paper, instead it accepts, stores and delivers binary blobs of data-messages.
RabbitMQ and messaging commonly use several jargon.
"Production" is the transmission itself. The program that sends the message is the "producer". We draw it with a “P” like this:
"Queue" is the name of the mailbox. It's inside RabbitMQ. Messages flow through RabbitMQ and applications, but are only stored inside "queues". A "queue" is not bound by any restrictions, it can store as many messages as you like, it is an essentially infinite buffer. Many "producers" can send messages to one "queue" and many "consumers" can try to receive data from one "queue". The "queue" has a name at the top and is drawn as follows:
"Consume" has the same meaning as receive. A "consumer" is a program that primarily waits for a message to be received. We draw it with “C”:
Keep in mind that producers, consumers, and brokers do not have to be on the same machine. In fact, this is not the case for most applications.
Hello World!
Our "Hello World" isn't too complicated, let's send a message, receive it and print it to the screen. To do this, you need two programs, one to send a message and the other to receive and output it.
The overall design looks like this:
The producer sends a message to the “hello” queue. The consumer receives the message from that queue.
RabbitMQ library
RabbitMQ uses several protocols. The one covered in this tutorial is called AMQP 0-9-1. To use RabbitMQ, you need a library that understands the same protocol as RabbitMQ. Libraries for almost all programming languages are available. You can also choose from multiple libraries in Python. * pika * py-amqp * py-amqplib A series of tutorials will use Pika, which is the library recommended by the RabbitMQ team. You can use the pip package management tool for installation.
$ sudo pip install pika==0.9.8
This installation depends on the pip and git-core packages, you need to install them first.
For Ubuntu:
$ sudo apt-get install python-pip git-core
For Debian:
$ sudo apt-get install python-setuptools git-core
$ sudo easy_install pip
For Windows: To install easy_install, run the Windows installer on setuptools.
> easy_install pip
> PIP install pika==0.9.8
The first program, send.py, sends a single message to the queue. The first thing you have to do is establish a connection with the RabbitMQ server.
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
We are now connecting to a broker on the local machine (“localhost”). If you want to connect to a broker on another machine, simply specify the machine name or IP address here.
Next, you need to make sure that the recipient's queue exists before you can send. If you send a message to a location that doesn't exist, RabbitMQ simply discards the message. Create a queue to deliver the message and name it “hello”:
channel.queue_declare(queue='hello')
Now you are ready to send the message. Our first message contains the string "* Hello World! *" And sends it to the * hello * queue.
RabbitMQ does not send messages directly to the queue, it must always go through * exchange *. But let's not delve into the details here, you can read more about * exchange * in Part 3 of this tutorial. All you need to know now is how to use the default * exchange *, which is identified by an empty string. This * exchange * is special, it allows you to specify exactly which queue the message should go to. You must specify the queue name in the routing_key parameter:
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
Before you exit the program, you need to make sure that you flush the network buffer to ensure that the message is actually delivered to RabbitMQ. You can do that by closing the connection gentlemanly.
connection.close()
Send does not work!
The second program, receive.py, receives the message from the queue and outputs it on the screen.
Again, you need to connect to the RabbitMQ server first. The code that connects to RabbitMQ is the same as before.
The next step is to make sure the queue exists, as before. Creating a queue using queue_declare is idempotent, this command can be run as many times as you like, and only one will be created.
channel.queue_declare(queue='hello')
You may be wondering why you declare the queue again, you have already declared it in the previous code. You can avoid this if you are sure that the queue already exists. For example, if the send.py program has already been executed. But we still don't know which program will be executed first. In such cases, it is recommended that both programs declare the queue repeatedly.
List of queues
You can see which queue is in RabbitMQ and how many messages there are. You can do that (as a privileged user) using the rabbitmqctl tool:
$ sudo rabbitmqctl list_queues
Listing queues ...
hello 0
...done.
(Omitted sudo on Windows)
Receiving a message from a queue is more complicated. It works by registering a callback function in the queue. This callback function is called by the Pika library each time a message is received. For this tutorial, this function prints the content of the message on the screen.
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
Next, we need to tell RabbitMQ that this callback function should receive the message from the “hello” queue.
channel.basic_consume(callback,
queue='hello',
no_ack=True)
The subscribing queue must exist for this command to succeed. Fortunately, that's for sure, I just created a queue using queue_declare.
The no_ack parameter will be described later.
And finally, it rushes into an endless loop, waiting for data and executing callbacks as needed.
print ' [*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()
Complete code for send.py:
1 #!/usr/bin/env python
2 import pika
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.queue_declare(queue='hello')
9
10 channel.basic_publish(exchange='',
11 routing_key='hello',
12 body='Hello World!')
13 print " [x] Sent 'Hello World!'"
14 connection.close()
Complete code for receive.py:
1 #!/usr/bin/env python
2 import pika
3
4 connection = pika.BlockingConnection(pika.ConnectionParameters(
5 host='localhost'))
6 channel = connection.channel()
7
8 channel.queue_declare(queue='hello')
9
10 print ' [*] Waiting for messages. To exit press CTRL+C'
11
12 def callback(ch, method, properties, body):
13 print " [x] Received %r" % (body,)
14
15 channel.basic_consume(callback,
16 queue='hello',
17 no_ack=True)
18
19 channel.start_consuming()
You can now try the program in the terminal. First, let's send a message using the send.py program:
$ python send.py
[x] Sent 'Hello World!'
The producer program send.py will stop after all executions. Let's receive it:
$ python receive.py
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'Hello World!'
Banzai! I was able to send my first message through RabbitMQ. As you may have noticed, the receive.py program does not exit. You can stay in preparation for receiving more messages and interrupt with Ctrl-C.
Try running send.py again in a new terminal.
You learned how to send and receive messages from named queues. Let's move on to Part 2 and build a simple work queue.
Recommended Posts