Official RabbitMQ tutorials --- Introduction, official rabbitmq tutorials ---

Source: Internet
Author: User
Tags rabbitmq

Official RabbitMQ tutorials --- Introduction, official rabbitmq tutorials ---

RabbitMQ is a message broker. The main idea is very simple: it receives and sends messages. You can think of it as a post office: When you send an email to your mailbox, you will be sure that the postman will eventually pass the email to your recipient. RabbitMQ is a mailbox, a post office, and a postman.


The main difference between RabbitMQ and the post office is that it does not process paper. On the contrary, it receives, stores, and transmits binary data-messages.


In general, RabbitMQ is a message.


Producing means that nothing except sending is done. A program that sends messages is a producer. We will plot it with "P:

Queue is the name of a mailbox. It lives in RabbitMQ. Even though messages have been circulated through RabbitMQ and your applications, they can be stored in only one queue clock. The queue is not bound with any restrictions. It can store messages you like as much as possible-it is equivalent to an unlimited cache. Many producers can send messages to a queue, and many consumers can try to receive messages from the queue. Queue will be drawn like the following figure:

Consuming is similar to receiving. Consumer is a program that is often waiting to receive messages. We use "C" to plot it:

Note that producer, consumer, and brokder do not need to reside on the same machine; in fact, they are not on the same machine in most applications.


Hello World!

(Use pika 0.9.8 Python client)

Our "Hello world" won't be too complicated-let's send a message, receive it, and print it on the screen. To make such a program, we need two programs: one for sending a message and one for receiving and printing it.


Our design will be like this:

The Producer sends a message to the "hello" queue. The consumer receives the message from that queue.

The RabbitMQ library RabbitMQ describes a protocol called AMQP. To use Rabbit, you will need a library that understands the protocol like Rabbit. Almost every programming language has such a library. There are not many libraries available for python: py-amqplib txAMQP pika we will use pika in this series of tutorials. You can use pip package management tool to install it: sudo pip install pika = 0.9.8 installation depends on pip and git-core packages, you may need to install them first. On ubuntu: sudo apt-get install python-pip git-core On Debian: sudo apt-get install python-setuptools git-coresudo easy_install pip on Windows: easy_install pippip install pika = 0.9.8


Send

Our first program send. py will send a message to the queue. The first thing we need to do is to establish a connection with RabbitMQ:

#!/usr/bin/env pythonimport pikaconnection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))channel = connection.channel()


Now we have connected to a local broker-due to localhost. If we want to connect to a machine with different brokers, We need to simply specify its name or IP address here.


Next, before sending, we need to make sure that the receiving queue already exists. If we send a message to a nonexistent address, RabbitMQ will discard the message. Create a queue named "hello" to be passed:

channel.queue_declare(queue="hello")


At that stage, we are ready to send a message. Our first message will contain only one string Hello World! And we send it to our hello queue.


A message in RabbitMQ may never be directly sent to the queue. It always needs to be exchanged. But we don't need to go into it-you can read more interaction information in the third part of this tutorial. What we only need to do is how to use an exchange identifier through an empty string. This kind of switch is special-it allows us to specify exactly which queue the message should enter. The queue name must be specified in the routing_key parameter:

channel.basic_publish(exchange='',routing_key="hello",body="Hello World!")print "[x] Sent 'Hello World!'"

Before exiting the program, we need to ensure that the Network cache has been refreshed and that our messages are indeed delivered to RabbitMQ. We can smoothly close the connection to process it.

connection.close()



Sending does not take effect if this is the first time you use RabbitMQ and you have not read the "Sent" message, then you may break your head and wonder what the possible error is. This broker may be turned on when there is not enough disk space (at least 1 GB space is required by default), so it rejects the message. Check the broker log file to make sure that limit is reduced if necessary. Configuration file documentation will show you how to set disk_free_limit.


Receive

Our second program is that receive. py will receive messages from the queue and print them on the screen.


Once again, we first need to connect to the RabbitMQ server. The connection code is the same as the previous one.


Next, make sure that the queue exists as before. Using queue_declare to create a queue is idempotent-you only need to create this queue once to run this command many times.

channel.queue_declare(queue='hello')

You may ask why we need to define a queue again-we have already defined it in the previous code. If we make sure that the queue already exists, we can avoid creating it. For example, if the send. py program runs before. But we are not sure which program runs first. Defining duplicate queues in two programs is a good practice.

Listing queues you may want to see what queues exist in RabbitMQ and how many messages there are. You can use the rabbitmqctl tool as follows: sudo rabbitmqctl list_queuesListing queues... hello 0... done. Ignore sudo on windows.


Receiving messages from a queue is complex. It subscribes to a callback function to the queue. No matter when we receive a message, this callback function will be called through the Pika library. In our example, this function prints the message content on the screen.

def callback(ch, method, properties, body):    print "[x] Received %r"%(body,)


Next, we need to tell RabbitMQ that this special callback function should receive messages from our hello queue:

channel.basic_consume(callback, queue='hello',no_ack=True)


For successful commands, make sure that we subscribe to an existing queue. Fortunately, we are confident about this-we have created a queue above-using queue_declare.


The no_ack parameter is described later.


Finally, we enter a callback that always polls the waiting data.

print "[*] Waiting for messages. To exit press CTRL+C"channel.start_consuming()


Put them together

Send. py code:

#!/usr/bin/env pythonimport pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))channel = connection.channel()channel.queue_declare(queue='hello')channel.basic_publish(exchange='',routing_key='hello',body='Hello World!')print "[x] Sent 'Hello World!'"connection.close()


Receive. py code:

#!/usr/bin/env pythonimport pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))channel = connection.channel()channel.queue_declare(queue='hello')print "[*] Waiting for messages. To exit press CTRL+C"def callback(ch, method, properties, body):    print "[x] Receieved %r"%(body,)    channel.basic_consume(callback, queue='hello',no_ack=True)channel.start_consuming()


The execution of the subsequent python files will not be translated. I believe anyone who uses python knows or can understand it.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.