Home Backend Development Python Tutorial First experience of operating RabbitMQ in Python (1)

First experience of operating RabbitMQ in Python (1)

Jan 17, 2017 pm 02:47 PM

Because I wanted to use Python to implement a distributed system to manage and monitor the content and operating status of the CDN, I got to know RabbitMQ by accident. Many people recommended it, such as Yu Feng's "Why should I choose RabbitMQ" and so on .

When the word MQ came into view, I spent several hours reading about what MQ is, that is, Message Queue (Message Queue). As the name suggests, message queue, a queue filled with messages, queue, data structure noun, is a data structure with first-in first-out characteristics. The message queue is nothing more than used to deliver messages, so what is its significance, what are its application scenarios, what features it has, what are its unique advantages, and why it should be used. These are a series of questions that come to my mind.

After a long search, I finally came to a superficial understanding that message queue is a communication method for application-to-application information transmission. For example, if you need to analyze the logs of multiple servers, you can use one process on each server to write data, that is, the required information, into a Mysql database table, and then write several processes to read the data in the table and process the data. The analysis is not very good, but soon the ugliness of this design became apparent... Do you want multiple programs to fetch data from a queue for processing? No problem, we hardcoded the number of programs...what? Also allow the program to dynamically distribute pressure as it increases and decreases dynamically? This is an example from the very popular "RabbitMQ+Python Introduction to Classic Rabbit and Rabbit Nest". Think about it, when my CDN transmits a lot of data, data distribution, processing, everything will be a problem. But I still don’t understand how Rabbit implements these things.

Conceptually speaking, RabbitMQ is the standard implementation of AMPQ (Advanced Message Protocol Queuing). It is said that if you are not familiar with AMQP, you will not be able to understand the RabbitMQ documentation. But we can only build a large understanding of the key concepts. The entire RabbitMQ implementation principle model is shown in the figure below. It is actually a producer and consumer model with a routing task distribution queue. As shown in the figure, the producer produces corresponding information and sends it to the router. The router distributes the information to different message queues based on the key information in the information, and then the consumer reads the data in different message queues. the process of.

First experience of operating RabbitMQ in Python (1)

#Broker: Simply put, it is the message queue server entity.
Exchange: Message exchange, which specifies the rules according to which messages are routed to which queue.
Queue: Message queue carrier, each message will be put into one or more queues.
Binding: Binding, its function is to bind exchange and queue according to routing rules.
Routing Key: Routing keyword, exchange delivers messages based on this keyword.
Vhost: virtual host. Multiple vhosts can be opened in a broker to separate permissions for different users.
Producer: Message producer is the program that delivers messages.
Consumer: Message consumer is the program that accepts messages.
Channel: Message channel. In each connection of the client, multiple channels can be established, and each channel represents a session task.

The process of using message queue is roughly as follows:

(1) The client connects to the message queue server and opens a channel.
 (2) The client declares an exchange and sets related attributes.
 (3) The client declares a queue and sets related attributes.
 (4) The client uses routing key to establish a binding relationship between exchange and queue.
 (5) The client delivers the message to exchange.

After understanding the general process and advantages of RabbitMQ, I started to trial RabbitMQ on my own Fedora.

According to the RabbitMQ official website, the installation needs to be downloaded from here

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

First experience of operating RabbitMQ in Python (1)


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

Enter the download path, /home/ sun5495/Downloads/

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

Change the permissions of the executable file and increase the execution permissions.

Then execute ./rabbitmq-server-3.3.0-1.noarch.rpm, and an error will be reported when running, unable to be installed.

It turns out that you need to install Erlang now. Try this command yum install erlang to get it done.

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
Copy after login

The installation is successful.

In order to set up RBMQ to start up, use the administrator account to execute the

chkconfig rabbitmq-server on
Copy after login

command to open and close the server

/sbin/service rabbitmq-server stop/start
Copy after login

The result is the following error when opening it
Starting rabbitmq-server (via systemctl): Job for rabbitmq-server.service failed. See 'systemctl status rabbitmq-server.service' and 'journalctl -xn' for details. [FAILED]

使用journalctl -xn命令打开日志,查看了下貌似是Erlang的某个文件拒绝访问,然后还提出了一大堆建议。

尝试一下

grep beam.smp /var/log/audit/audit.log | audit2allow -M mypolsemodule -i mypol.pp/sbin/service rabbitmq-server start
Copy after login

First experience of operating RabbitMQ in Python (1)

既然RabbitMQ安装也运行成功了,那么我就来尝尝RabbitMQ的鲜吧。就从官网上的例子一步一笔来做好了。

由于我使用的是Python,那么就需要安装一些支持RabbitMQ的库来进行操作,其中包括

py-amqplib,txAMQP,pika这几种,按照官网的tutorial,我也安装了pika。

pip install pika
Copy after login

从最简单的收发消息开始。即一端发送消息,一端接收消息。

First experience of operating RabbitMQ in Python (1)

发送方即生产者,首先要创建与RabbitMQ服务器的连接,

#!/usr/bin/env pythonimport pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(              
 'localhost'))channel = connection.channel()
Copy after login

此处服务器连接本地localhost,也可以指定ip或者主机名。

其次发送方需要声明一个队列,比如命名为sayhello

channel.queue_declare(queue='sayhello')
Copy after login

此时我们就可以发送消息了。由于第一个小案例比较简单,没有经过路由器,因此发送消息时,指定路由为空即可。

channel.basic_publish(exchange='',                        
routing_key='hello',                                    
body='hello world')print "Sent ‘hello world'"
Copy after login

最后关闭连接即可。

connection.close()
Copy after login

接收方即消费者,需要从队列上获取数据,因此也需要绑定一个队列

channel.queue_declare(queue='hello')
Copy after login

同时,由于接收方的工作方式是基于队列的消息执行一个回调函数,当收到消息时,Pika就会执行相应的回调函数,因此我们需要定义此函数。

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

接下来我们需要初始化这个消费者,并对消费者进行启动。

channel.basic_consume(callback,                      
queue='hello',                      
no_ack=True)print ' [*] Waiting for messages. To exit press CTRL+C'channel.start_consuming()
Copy after login

OK执行成功。

接下来就逐步的深入体验RabbitMQ的独特魅力。

以上就是Python操作RabbitMQ初体验(一)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles