Created
July 16, 2019 08:49
-
-
Save foowaa/275a05e935d13fb2ea427a7a7e7b5834 to your computer and use it in GitHub Desktop.
redis queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment