The following article shows how to useredisto build a simple multi-producer, multi-consumer Queue with an interface similar to thepython
standardlib queue. With this queue you can easily share data between multiple processes or offload time consumig calculations to multiple worker processes.
To store the data we use theredis list data type. Redis Lists stores simple strings sorted by insertion order.
The following redis commands are used:
-
rpushInsert an element at the tail of the list
-
blpopGet an element from the head of the list, block if list is empty
-
lpopGet an element from the head of the list, return nothing list is empty
-
llenReturn the length of the list
The implementation uses theredis-pylibrary to talk to the server.
import redis
class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, name, namespace='queue', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.__db= redis.Redis(**redis_kwargs)
self.key = '%s:%s' %(namespace, name)
def qsize(self):
"""Return the approximate size of the queue."""
return self.__db.llen(self.key)
def empty(self):
"""Return True if the queue is empty, False otherwise."""
return self.qsize() == 0
def put(self, item):
"""Put item into the queue."""
self.__db.rpush(self.key, item)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args block is true and timeout is None (the default), block
if necessary until an item is available."""
if block:
item = self.__db.blpop(self.key, timeout=timeout)
else:
item = self.__db.lpop(self.key)
if item:
item = item[1]
return item
def get_nowait(self):
"""Equivalent to get(False)."""
return self.get(False)
使用方法:
>>> from RedisQueue import RedisQueue
>>> q = RedisQueue('test')
>>> q.put('hello world')
Now if we have a look at the redis database with theredis-cli
client
it shows the expected results:
redis 127.0.0.1:6379> keys *
1) "queue:test"
redis 127.0.0.1:6379> type queue:test
list
redis 127.0.0.1:6379> llen queue:test
(integer) 1
redis 127.0.0.1:6379> lrange queue:test 0 1
1) "hello world"
We can get the item from a different script with:
>>> from RedisQueue import RedisQueue
>>> q = RedisQueue('test')
>>> q.get()
'hello world'
A subsequent call ofq.get()
will block until anotherone puts a new item into the Queue.
The next step would be to an endoder/decoder (e.gpython-json) to the Queue so that you are not limited to send strings.
There alredy exists the nice and simplehotqueuelibrary which has the same interface as the above example and provides encoding/decoding.
Other mentionable queue implementations with a redis backend are:
-
flask-redisA basic Message Queue with Redis for flask.
-
celeryAn asynchronous task queue/job queue based on distributed message passing. Much more advanced. Can be used with different storage backends.
-
rqSimple python library for queueing jobs and processing them in the background with workers.
-
resqueis a Redis-backed Ruby library for creating background jobs, placing them on multiple queues, and processing them later. Used at github. Includes a nice monitoring
web interface.
-
pyresA resque clone in python.
FRom:
http://peter-hoffmann.com/2012/python-simple-queue-redis-queue.html
分享到:
相关推荐
考虑到“简单”和“易用”的特点,一个可能的实现是使用Python的内置`queue`模块,它提供了线程安全的队列操作。 2. **生产者(Producer)**:生产者是将消息放入队列的组件。你可以编写一个函数或类,接收用户输入...
任务队列 环境准备 Python Redis # pip install -i http://pypi.douban.com/simple redis RQ # pip install -i http://pypi.douban.com/simple rq Redis Server # docker pull redis:latest # docker run -d -p 6379...
1. **简单API**:`django_simple_queue` 提供了一个简单的API,使得添加、删除和管理任务变得直观且易于实现。 2. **任务类型**:支持不同类型的任务,包括一次性任务和周期性任务,可以按需设定任务的执行频率。 ...
"Simple job queues for Python"通常指的是用于处理异步任务和后台工作的解决方案,它允许我们将任务放入队列,然后由工作进程在后台处理。RQ(Resque for Python)是一个流行的选择,它是从Ruby的Resque库移植过来...
A simple message batch scheduling module based on message queue, zookeeper, and python thread operation. 一个从消息消费业务场景中总结,基于队列组件+zookeeper+python线程操作实现的消息批处理场景调度模块....
Laravel提供了多种队列驱动,包括数据库、Redis、SQS、Beanstalkd等,而“l5-stomp-queue”则添加了对Stomp协议的支持。 Stomp(Simple Text Oriented Messaging Protocol)是一种简单、跨平台的文本消息协议,常...
最新Python3.5零基础+高级+完整项目(28周全)培训视频学习资料;本资料仅用于学习。 【课程内容】 第1周 开课介绍 python发展介绍 第一个python程序 变量 字符编码与二进制 字符编码的区别与介绍 用户交互程序 if ...
"project-sendEmail-workers" 是一个基于Python的项目,主要用于实现邮件发送功能,特别是与工作流程相关的批量邮件发送。从项目名称来看,它可能是为自动化发送电子邮件而设计的一个工作线程或者任务调度系统。下面...