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','123456')
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 1

consumer消费者

# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika credentials = pika.PlainCredentials('admin','123456')
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 0

队列持久化

当rabbitMQ意外宕机时,可能会有持久化保存队列的需求(队列中的消息不消失)。

producer

# Cheng
# !/usr/bin/env python
import pika credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',5672,'/',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=2, # 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','123456')
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='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 0

广播模式

当producer发送消息到队列后,所有的consumer都会收到消息,需要注意的是,此模式下producer与concerned之间的关系类似与广播电台与收音机,如果广播后收音机没有接受到,那么消息就会丢失。

建议先执行concerned

concerned

# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika credentials = pika.PlainCredentials('admin','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',5672,'/',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','123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'192.168.56.19',5672,'/',credentials))
channel = connection.channel() channel.exchange_declare(exchange='Clogs',
type='fanout') message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='Clogs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()

python RabbitMQ队列使用的更多相关文章

  1. python RabbitMQ队列使用(入门篇)

    ---恢复内容开始--- python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种que ...

  2. python RabbitMQ队列/redis

    RabbitMQ队列 rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或 ...

  3. python学习笔记-(十五)RabbitMQ队列

    rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或者同属于同一父进程下的 ...

  4. Python开发【十一章】:RabbitMQ队列

    RabbitMQ队列 rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或 ...

  5. Python自动化 【第十一篇】:Python进阶-RabbitMQ队列/Memcached/Redis

     本节内容: RabbitMQ队列 Memcached Redis 1.  RabbitMQ 安装 http://www.rabbitmq.com/install-standalone-mac.htm ...

  6. Day10 - Python协程、异步IO、redis缓存、rabbitMQ队列

    Python之路,Day9 - 异步IO\数据库\队列\缓存   本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitM ...

  7. Python RabbitMQ消息队列

    python内的队列queue 线程 queue:不同线程交互,不能夸进程 进程 queue:只能用于父进程与子进程,或者同一父进程下的多个子进程,进行交互 注:不同的两个独立进程是不能交互的.   ...

  8. Python之协程、异步IO、redis缓存、rabbitMQ队列

    本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitMQ队列 Redis\Memcached缓存 Paramiko SS ...

  9. 【python】-- RabbitMQ 队列消息持久化、消息公平分发

    RabbitMQ 队列消息持久化 假如消息队列test里面还有消息等待消费者(consumers)去接收,但是这个时候服务器端宕机了,这个时候消息是否还在? 1.队列消息非持久化 服务端(produc ...

随机推荐

  1. JAVA基础补漏--多态

    Fu obj = new ZI(); 访问成员变量规则 编译看左,运行看左. obj.num; 1.直接通过对象名访问成员变量:看等号左右是谁,优先用谁,没有则往上找. obj.getnum(); 2 ...

  2. Python caffe.TEST Example(Demo)

    下面提供了caffe python的六个测试demo,大家可以根据自己的需求进行修改. Example 1 From project FaceDetection_CNN-master, under d ...

  3. ACM-ICPC北京站总结

    失踪人口回归.... 第一次ACM比赛还是比较紧张的,总体来说发挥还是有一点失常. day1热身赛 一共四道去年和前年的北京站的题目....似乎都是银牌题及以下难度.半个小时我们就完成了嘴巴AK,然而 ...

  4. Pandas索引和选择数据

    在本章中,我们将讨论如何切割和丢弃日期,并获取Pandas中大对象的子集. Python和NumPy索引运算符"[]"和属性运算符".". 可以在广泛的用例中快 ...

  5. DPDK编程指南 2.概述

    本章节给出了DPDK架构的一个全局概述. DPDK的主要目的就是为数据面快速报文处理应用程序提供一个简洁完整的框架.用户可以通过代码来理解其中使用的一些技术,构建自己的应用程序或添加自己的协议栈.Al ...

  6. LeetCode第[19]题(Java):Remove Nth Node From End of List(删除链表的倒数第N个节点)

    题目:删除链表的倒数第N个节点 难度:Medium 题目内容: Given a linked list, remove the n-th node from the end of list and r ...

  7. 缓存技术内部交流_01_Ehcache3简介

    参考资料: http://www.ehcache.org/documentation/3.2/getting-started.html http://www.ehcache.org/documenta ...

  8. 在Window工作区按下鼠标左键拖动窗体

    Window.DragMove(): 允许使用在窗口工作区的暴露区域上方按下其鼠标左键的鼠标来拖动窗口.(窗口工作区:除去窗体的title.bottom后的剩余部分空间) 使用该方法时注意:一定要在鼠 ...

  9. Ajax基础(五)--封装库

    jQuery ajax请求的基本语法: 一.封装为对象: ajax.txt代码: {"id":"102","username":" ...

  10. linux中的权限管理命令

    一. 改变文件或目录的权限:chmod 命令详解 命令名称:chmod 命令所在路径:/bin/chmod 执行权限:所有用户 语法:chmod [{ugoa}{+-=}{rwx}] [文件或目录] ...