python RabbitMQ队列使用(入门篇)
---恢复内容开始---
python RabbitMQ队列使用
关于python的queue介绍
关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下的线程间或者父进程与子进程之间进行队列通讯,并不能进行程序与程序之间的信息交换,这时候我们就需要一个中间件,来实现程序之间的通讯。
RabbitMQ
MQ并不是python内置的模块,而是一个需要你额外安装(ubunto可直接apt-get其余请自行百度。)的程序,安装完毕后可通过python中内置的pika模块来调用MQ发送或接收队列请求。接下来我们就看几种python调用MQ的模式(作者自定义中文形象的模式名称)与方法。
RabbitMQ设置远程链接账号密码
启动rabbitmq web服务:
2.远程访问rabbitmq:自己增加一个用户,步骤如下:
l1. 创建一个admin用户:sudo rabbitmqctl add_user admin 123123
l2. 设置该用户为administrator角色:sudo rabbitmqctl set_user_tags admin administrator
l3. 设置权限:sudo rabbitmqctl set_permissions -p '/' admin '.' '.' '.'
l4. 重启rabbitmq服务:sudo service rabbitmq-server restart
之后就能用admin用户远程连接rabbitmq server了。
轮询消费模式
此模式下,发送队列的一方把消息存入mq的指定队列后,若有消费者端联入相应队列,即会获取到消息,并且队列中的消息会被消费掉。
若有多个消费端同时连接着队列,则会已轮询的方式将队列中的消息消费掉。
接下来是代码实例:
producer生产者
# !/usr/bin/env python
import pika
credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',5672,'/',credentials))
channel = connection.channel() # 声明queue
channel.queue_declare(queue='balance') # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
routing_key='balance',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
发送过队列后,可在MQ服务器中查看队列状态
[root@localhost ~]# rabbitmqctl list_queues
Listing queues ...
hello
consumer消费者
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',5672,'/',credentials))
channel = connection.channel() # You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
channel.queue_declare(queue='balance') def callback(ch, method, properties, body):
print(" [x] Received %r" % body) channel.basic_consume(callback,
queue='balance',
no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
接收队列后,查看一下队列状态
[root@localhost ~]# rabbitmqctl list_queues
Listing queues ...
hello
队列持久化
当rabbitMQ意外宕机时,可能会有持久化保存队列的需求(队列中的消息不消失)。
producer
# Cheng
# !/usr/bin/env python
import pika credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',,'/',credentials))
channel = connection.channel() # 声明queue
channel.queue_declare(queue='durable',durable=True) # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
routing_key='durable',
body='Hello cheng!',
properties=pika.BasicProperties(
delivery_mode=, # make message persistent
)
)
print(" [x] Sent 'Hello cheng!'")
connection.close()
执行后查看队列,记下队列名字与队列中所含消息的数量
[root@localhost ~]# rabbitmqctl list_queues
Listing queues ...
durable 1
#重启rabbitmq
[root@localhost ~]# systemctl restart rabbitmq-server
#重启完毕后再次查看
[root@localhost ~]# rabbitmqctl list_queues
Listing queues ...
durable #队列以及消息并未消失
执行消费者代码
cunsumer
# Cheng
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',,'/',credentials))
channel = connection.channel() # You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
channel.queue_declare(queue='durable',durable=True) def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_consume(callback,
queue='durable',
#no_ack=True
) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
可正确接收到信息。
再次查看队列的情况。
[root@localhost ~]# rabbitmqctl list_queues
Listing queues ...
durable
广播模式
当producer发送消息到队列后,所有的consumer都会收到消息,需要注意的是,此模式下producer与concerned之间的关系类似与广播电台与收音机,如果广播后收音机没有接受到,那么消息就会丢失。
建议先执行concerned
concerned
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',,'/',credentials))
channel = connection.channel() channel.exchange_declare(exchange='Clogs',
type='fanout') result = channel.queue_declare(exclusive=True) # 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
queue_name = result.method.queue channel.queue_bind(exchange='Clogs',
queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body):
print(" [x] %r" % body) channel.basic_consume(callback,
queue=queue_name,
no_ack=True) channel.start_consuming()
producer
import pika
import sys credentials = pika.PlainCredentials('admin','')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',,'/',credentials))
channel = connection.channel() channel.exchange_declare(exchange='Clogs',
type='fanout') message = ' '.join(sys.argv[:]) or "info: Hello World!"
channel.basic_publish(exchange='Clogs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()
谢土豪
如果有帮到你的话,请赞赏我吧!

python RabbitMQ队列使用(入门篇)的更多相关文章
- python RabbitMQ队列使用
python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下 ...
- 学习笔记之盘一盘 Python 系列 1 & 2 - 入门篇
盘一盘 Python 系列 1 & 2 - 入门篇 https://mp.weixin.qq.com/s?__biz=MzIzMjY0MjE1MA==&mid=2247486473&a ...
- RabbitMq学习一入门篇(hello world)
简介 RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写,支持多种客户端,如:Python.Ruby..NET.Java,也是众多消息队列中表现不俗的一员,作用就是提高系统的并发 ...
- python RabbitMQ队列/redis
RabbitMQ队列 rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或 ...
- python学习之路入门篇
本文是up学习python过程中遇到的一些问题及总结归纳,本小节是入门篇. python基本语法 循环.分支不多赘述. 模块:一个.py文件就是一个模块. 文件和异常 模式 含义解释 “r” 读模式 ...
- 学习python之路_入门篇A
偶尔经同事的介绍进入了金角大王的博客里,看到大王编写的文章都是关于python编程的,由于自己一直也是做软件测试方面的工作,也一直想往自动化测试方面发展,了解到利用python可以进行自动化测试操作, ...
- 小白的 Python 修炼手册:入门篇
Life is short, you need Python.(人生苦短,我用 Python.) --Bruce Eckel 前言 听说现在是全民 Python 的时代,虽然不知道事实如何,但学会 P ...
- Python selenium自动化测试框架入门实战--登录测试案例
本文为Python自动化测试框架基础入门篇,主要帮助会写基本selenium测试代码又没有规划的同仁.本文应用到POM模型.selenium.unittest框架.configparser配置文件.s ...
- Python自动化 【第十一篇】:Python进阶-RabbitMQ队列/Memcached/Redis
本节内容: RabbitMQ队列 Memcached Redis 1. RabbitMQ 安装 http://www.rabbitmq.com/install-standalone-mac.htm ...
随机推荐
- hadoop权威指南 chapter2 MapReduce
MapReduce MapReduce is a programming model for data processing. The model is simple, yet not too sim ...
- IRQL_NOT_LESS_OR_EQUAL的问题最终算攻克了
今日想提高我那台古董笔记本extensa 4620Z的执行效率.方便我编程. 我先用万能的硬件检測工具,反正也就那几个流氓软件看了下.内存是ddr2的.我也顺带补习了一下许久不碰的硬件知识.ddr2和 ...
- CVE-2016-5343分析
最近在学习android内核漏洞,写篇博做个记录,也算是所学即用. https://www.codeaurora.org/multiple-memory-corruption-issues-write ...
- OD: Heap Exploit : DWORD Shooting & Opcode Injecting
堆块分配时的任意地址写入攻击原理 堆管理系统的三类操作:分配.释放.合并,归根到底都是对堆块链表的修改.如果能伪造链表结点的指针,那么在链表装卸的过程中就有可能获得读写内存的机会.堆溢出利用的精髓就是 ...
- iframe 元素
iframe 元素会创建包含另外一个文档的内联框架(即行内框架). 可以访问:http://www.w3school.com.cn/tags/tag_iframe.asp
- 黑马程序员——HTML语言
------<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS ...
- 使用Gird++打印出现“Retrieving the COM class factory for component with CLSID”的解决办法
我们的接口需要返回一个gird++生成PDF文件的二进制数据,在本地测试都很好,发布到服务器上一直出现“Retrieving the COM class factory for component w ...
- SQL流程控制语句学习(三):while break continue
1.while语法 while 布尔表达式 {sql语句或语句块} break --跳出本层循环 {sql语句或语句块} continue --跳出本次循环 {sql语句或语句块} 2.whi ...
- tomcat 远程 调试 eclipse
windows系统: 修改catalina.bat 端口9000 SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.compiler=NONE ...
- C#类的基本用法
Preson类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...