Python Operation Rabbitmq First Experience (i)

Source: Internet
Author: User
Tags rabbitmq
Because want to use Python to implement a set of distributed system, to manage and monitor CDN content and running state, stumbled to know RABBITMQ, recommended many people, such as Yu Feng "Why should I choose RABBITMQ" and so on.

I spent hours reading about MQ, the message queue, when I was greeted by the word MQ. As the name implies, a message queue, a queue full of messages, a queue, a data structure noun, a data structure with FIFO characteristics. Message Queuing is nothing more than a message, so what does it mean, where the scenario is, what features it has, and what its unique advantages are, and why, these are all a series of questions that come to mind.

After a series of searches, the superficial understanding of Message Queuing is the way in which the application's information is communicated to the application. For example, you need to analyze the logs of multiple servers, it is completely possible for each server to use a process to write data to a table in a MySQL database, that is, the required information, and then write a few processes, read the table data, data analysis is not very good, but soon, the ugly place of this design appears ... Do you want multiple programs to take data from one queue to handle it? No problem, we have a good number of hard-coded programs ... What the? Also be able to allow the program to dynamically increase and decrease the time when dynamic pressure distribution? This is a very popular example of the Rabbitmq+python Classic Bunny and rabbit den. Think of it too, when my CDN transmits a lot of data, the data is distributed, processed, everything is a problem. But still do not understand, rabbit how to achieve these things.

Conceptually, RABBITMQ is the standard implementation of the AMPQ (Advanced Message Protocol queue), which is said to be unfamiliar with AMQP and will not understand RABBITMQ documentation. But you can only build a big understanding of key concepts. The implementation of the entire RABBITMQ model, in fact, is a lead by the task distribution queue producer and consumer model. , that is, producers produce the corresponding information, sent to the router, the router according to the information key key information, the information distributed to different message queues, and then by the consumer to the different message queue to read the data process.

Broker: The Message Queuing server entity is simply the case.
Exchange: A message switch that specifies what rules the message is routed to and to which queue.
Queue: A message queue carrier in which each message is put into one or more queues.
Binding: Bind, which is the role of binding exchange and queue according to routing rules.
Routing key: The routing keyword, exchange messages are delivered based on this keyword.
Vhost: Virtual host, a broker can open multiple vhost, as a separate user permissions.
Producer: The message producer is the program that delivers the message.
Consumer: The message consumer is the program that receives the message.
Channel: The message channels, in each connection of the client, multiple channels can be established, each channel represents a session task.

The use of Message Queuing is probably as follows:

(1) The client connects to the Message Queuing server and opens a channel.
(2) The client declares an exchange and sets the related properties.
(3) The client declares a queue and sets the related properties.
(4) The client uses routing key to establish a good binding relationship between Exchange and queue.
(5) Clients post messages to exchange.

Having understood RABBITMQ's approximate process and advantages, I started experimenting with rabbitmq on my fedora.

According to RABBITMQ website, installation needs to download from here

Http://www.rabbitmq.com/download.html


Click to download each version of the binary package, I downloaded the rabbitmq-server-3.3.0-1.noarch.rpm

Go to download path,/home/sun5495/downloads/

[Sun5495@localhost downloads]# sudo chmod 777 rabbitmq-server-3.3.0-1.noarch.rpm

Change executable permissions to increase execution permissions.

Then execute the./rabbitmq-server-3.3.0-1.noarch.rpm, run an error, unable to install.

It is now necessary to install Erlang, try this command yum install Erlang.

Then use the root user to execute

RPM--import http://www.rabbitmq.com/rabbitmq-signing-key-public.asc Yum Install rabbitmq-server-3.3.0-1.noarch.rpm

The installation was successful.

To set up the RBMQ boot, use the Administrator account to perform

Chkconfig Rabbitmq-server on

To turn server use commands on and off

/sbin/service Rabbitmq-server Stop/start

When the results are open, the error is as follows
Starting Rabbitmq-server (via Systemctl): Job for Rabbitmq-server.service failed. See ' systemctl status Rabbitmq-server.service ' and ' journalctl-xn ' for details. [FAILED]

Use the JOURNALCTL-XN command to open the log, view a file that looks like Erlang is denied access, and then make a lot of suggestions.

Try

grep Beam.smp/var/log/audit/audit.log | Audit2allow-m mypolsemodule-i mypol.pp/sbin/service rabbitmq-server start

Since the RABBITMQ installation has also run successfully, then I will try RABBITMQ's fresh. Just take a step from the official online example to do it.

Since I'm using python, I need to install some libraries that support RABBITMQ, including

Py-amqplib,txamqp,pika these kinds, according to the official website of tutorial, I also installed Pika.

Pip Install Pika

Start with the simplest message to send and receive. That is, one end sends a message and one end receives it.

The sender is the producer, first to create a connection to the RABBITMQ server,

#!/usr/bin/env pythonimport pikaconnection = Pika. Blockingconnection (Pika. Connectionparameters (               ' localhost ')) channel = Connection.channel ()

Here the server connects to local localhost, or you can specify an IP or hostname.

Next, the sender needs to declare a queue, for example named SayHello

Channel.queue_declare (queue= ' SayHello ')

At this point we can send a message. Because the first small case is relatively simple and does not pass through the router, the specified route is empty when the message is sent.

Channel.basic_publish (exchange= ",                        routing_key= ' Hello ',                                    body= ' Hello World ') print" Sent ' Hello World ' "

Finally, close the connection.

Connection.close ()

The receiver, the consumer, needs to get the data from the queue, so it needs to bind a queue

Channel.queue_declare (queue= ' Hello ')

At the same time, because the receiver works by executing a callback function based on the queue message, Pika executes the corresponding callback function when the message is received, so we need to define this function.

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

Next we need to initialize the consumer and start the consumer.

Channel.basic_consume (callback,                      queue= ' Hello ',                      no_ack=true) print ' [*] waiting for messages. To exit Press CTRL + C ' channel.start_consuming ()

OK to execute successfully.

The next step is to deeply experience RABBITMQ's unique charm.

Above is the Python operation Rabbitmq first Experience (a) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • 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.