RabbitMQ (Python implementation) One of the learning: simple two-point transmission "Hello world" implementation

Source: Internet
Author: User
Tags message queue rabbitmq

I. BASIC configuration

Note RABBITMQ support for Python, Java, Ruby, PHP, C # and other languages, this blog is mainly for the python explanation. This blog installation configuration is based on the Ubuntu system.

1.1 Installation Configuration Epel source

$ RPM-UVH http://dl.fedoraproject.org/pub/ease-6-8. noarch.rpm

1.2 Installing Erlang

$: Yum-y install Erlang  or $:sudo apt-get install Erlang

1.3 Installing Rabbitmq-server

$: yum-y Install rabbitmq-server or $: sudo apt-get install Rabbitmq-server

1.4 Start/Stop Rabbitmq-server

$: sudo service rabbitmq-server start$: sudo service rabbitmq-server stop

1.5 Installing RABBITMQ Libraries

RABBITMQ follows the AMQP protocol, in order to use RABBITMQ, you need a library to interpret this protocol, and for Python you need to install any one of the following library functions:

>py-amqplib>txamqp>pika

This post takes the Pika library as an example, installed as follows:

$:sudo pip Install pika==0.9.8 or
$:sudo Apt-get Install pika==0.9.8

Note: The following is performed on the premise that the Rabbitmq-server is started and runs on standard port 5672.

Two. translation of the English version

2.1 Introduction

RABBITMQ equivalent to a message agent, he finished receiving and forwarding the message function, you can think of it as a post office, play a role in the relay. RABBITMQ will use a number of technical terms, as follows:

>producer: The program used to send messages is called a Producer, and we use ' P ' to denote:

>queue: Queue, equivalent to the role of the mailbox, he has been created after the survival and RABBITMQ, although the message can flow between your programs, but in this middle of the process, the message must exist in the queue, queue no size limit, you can save countless messages, (If you have to set aside 1GB of hard disk space), he is the equivalent of an unrestricted cache. Multiple producer can send messages to the same queue, and multiple consumer can also receive messages from the same queue. A queue can be represented by the following diagram, which is the name of the queue.

>consumer: A program to receive messages called Consumer, we use the following diagram to represent:

Note that for producer and consumer you may not be on the same host, and subsequent posts will be introduced.

2.2 Two-point transmission "Hello world!" ”

Requires two programs, one for sending "Hello world! ", a program used to receive" Hello world! and print to the top of the screen. The model is as follows:

We create a queue named Hello. Producer sends a message to the Queue,consumer of hello to receive the message from the queue named Hello.

2.3sending (send code implementation)

The model is as follows:

First we need to write a send.py program, which will send a message to the queue, the first thing we do is to establish a connection with Rabbitmq-server, the code is as follows:

Import= Pika. Blockingconnection (Pika. Connectionparameters (host='localhost'= Connection.channel ()

If we want to establish a connection with a different host, simply change the ' localhost ' to an IP address.

Next, we need to determine the presence of the queue that accepts the message, and if we send the message to a nonexistent queue, then RABBITMQ automatically discards the message, let's create a Message Queuing queue named ' Hello '

Channel.queue_declare (queue='hello')

In RABBITMQ, a message cannot be sent directly to the queue, it needs to go through an exchange, and a subsequent post will talk about, now we just set Exchange to an empty string.

Exchange is special, and he will identify our message to which message queue Queue,queue's name needs to be identified by Routing_key, and exchange determines which Message Queuing queue the message is sent to by Routing_key. The code is as follows:

Channel.basic_publish (exchange=", routing_key='hello', body='  Hello world! ' )print"[X] Sent ' Hello world! ' "

Before exiting the program, we need to clean up the cache and determine our message "Hello world! "Really sent to RABBITMQ, we can close the connection to complete, the code is as follows:

Connection.close ()

The complete send.py code is as follows:

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

2.4Receiving (Receive code implementation)

The model is as follows:

Our receiving program receive.py will receive the message and print it on the screen.

Also first, we need to establish a connection with Rabbitmq-server, the code and send.py are basically the same, the code is as follows:

Import= Pika. Blockingconnection (Pika. Connectionparameters (host='localhost')) channel=connection.channel ()

Next, as before, to determine the existence of a queue of queues, to create a queue with Queue_declare (), we can run many times for this command, but only a queue with the name Hello is present. The code is as follows:

Channel.queue_declare (queue='hello')

Perhaps you will ask why we want to create a queue with the name Hello again, before we have established Ah, of course, if we make sure the queue is already there, we can not add this code. For example, if the send.py program has been run before, but we are not sure which program to run first, it is necessary to declare the queue in two programs at the same time.

For receive.py, we are going to define a callback function that, when we receive the message, the Pika library calls the callback function, and in our program, the callback function prints the received message on the screen. The function code is as follows:

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

Next we need to tell RABBITMQ that the function of this special function, callback (), is to receive messages from the queue of Hello, which is the following code:

Channel.basic_consume (callback,queue='hello', no_ack=true)

For No_ack in the code, the following blog will be mentioned.

Finally, we open a thread that never stops waiting for the message and runs the callback () function when needed. The code is as follows:

Print ' [*] waiting for message. To exit Press CTRL + C'channel.start_consuming ()

The complete receive.py code is as follows:

Importpikaconnection=Pika. Blockingconnection (Pika. Connectionparameters (Host='localhost')) Channel=Connection.channel () channel.queue_declare (Queue='Hello')Print '[*] waiting for messages. To exit Press CTRL + C'defCallback (ch, method, properties, body):Print "[x] Received%r"%(body,) Channel.basic_consume (callback, queue='Hello', No_ack=True) channel.start_consuming ()

2.5 Code Testing

First open a command-line window, run the send.py code, run and result as follows:

' Hello world! '

send.py stops every time it runs, let's run the received code receive.py, and the results are as follows:

$: Python receive.py [ for messages. To exit Press CTRL+'Hello world! '

You will see that received.py runs up and does not stop, always waiting for the incoming message, if you want to stop, CTRL + C.

Continuing to run send.py in a new command-line window, the command-line window running receive.py will continue to output the appropriate information.

2.6 Section rabbitmq-server command-line Action commands

1) View the names of each queue and the number of messages in the queue

$: sudo rabbitmqctl list_queues

For example

$: sudo rabbitmqctl list_queueslisting queues ... hello 0...done.    

2) View the names of each exchange

$: sudo rabbitmqctl list_exchanges

RabbitMQ (Python implementation) One of the learning: simple two-point transmission "Hello world" implementation

Related Article

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.