[PYTHON] RabbitMQ Tutorial 1 ("Hello World!")

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.

Prerequisites

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 a problem occurs

If you encounter any issues through this tutorial, you can contact us through the mailing list.

Introduction

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.

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!

(Using pika 0.9.8 Python client)

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

Send

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!

If you're new to RabbitMQ and don't see a "sent" message, you may be wondering what's wrong. The broker may have started without enough free disk space (requires at least 1GB of free space by default) and refused to accept the message. Check the broker log file and remove the constraints if necessary. The configuration file documentation shows how to set disk_free_limit.

Receive

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()

All summary

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

RabbitMQ Tutorial 1 ("Hello World!")
Hello world
RabbitMQ Tutorial 5 (Topic)
Pymacs hello world
RabbitMQ Tutorial 6 (RPC)
RabbitMQ Tutorial (1) -From Installation to Hello World (Official Site Translation)
RabbitMQ Tutorial 4 (Routing)
cython hello world
Flask tutorial (from installation to hello world)
RabbitMQ Tutorial 2 (Work Queue)
web2py memo: Hello World
Hello, World with Docker
Hello World on Django
Django's first Hello World
Hello world with flask
Draw hello world with mod_wsgi
Hello World with Flask + Hamlish
Until hello world with zappa
Programming language in "Hello World"
Hello World in GO language
Hello World (beginners) on Django
Python starting with Hello world!
Let's do "Hello World" in 40 languages! !!
Hello, world! With virtual CAN communication
Introduction to TensorFlow --Hello World Edition
RabbitMQ Tutorial 5 (Topic)
RabbitMQ Tutorial 6 (RPC)
RabbitMQ Tutorial 4 (Routing)
RabbitMQ Tutorial 2 (Work Queue)
RabbitMQ Tutorial 1 ("Hello World!")
Hello world! (Minimum Viable Block Chain)
[Note] Hello world output with python
cout << "Hello, World! \ N" in python
Hello World in Flask [Appropriate memo]
Code: 2 "Hello World" in "Choregraphe-Python script"
Hello World! By QPython with Braincrash
Python #Hello World for super beginners
Introduction to Ansible Part 1'Hello World !!'
[Python] Web application from 0! Hands-on (2) -Hello World-
Hello World and face detection with opencv-python 4.2
Hello World with Raspberry Pi + Minecraft Pi Edition
How to build Hello, World on #Nix
Hello world instead of localhost in Django
(For myself) Django_1 (Basic / Hello World / Template)
How to display Hello world in python
Hello World! By QPython with Brainfu * k