Skip to content

Commit ccfee03

Browse files
committed
新增redis队列测试
1 parent 39e8377 commit ccfee03

1 file changed

Lines changed: 102 additions & 0 deletions

File tree

tools/redis_queue.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""
5+
@author: zhanghe
6+
@software: PyCharm
7+
@file: redis_queue.py
8+
@time: 2016/10/24 下午10:42
9+
"""
10+
11+
12+
import sys
13+
import redis
14+
15+
16+
class RedisQueue(object):
17+
"""Simple Queue with Redis Backend"""
18+
19+
def __init__(self, name, namespace='queue', **redis_kwargs):
20+
"""The default connection parameters are: host='localhost', port=6379, db=0"""
21+
self.__db = redis.Redis(**redis_kwargs)
22+
self.key = '%s:%s' % (namespace, name)
23+
24+
def qsize(self):
25+
"""Return the approximate size of the queue."""
26+
return self.__db.llen(self.key)
27+
28+
def empty(self):
29+
"""Return True if the queue is empty, False otherwise."""
30+
return self.qsize() == 0
31+
32+
def put(self, item):
33+
"""Put item into the queue."""
34+
self.__db.rpush(self.key, item)
35+
36+
def get(self, block=True, timeout=None):
37+
"""Remove and return an item from the queue.
38+
39+
If optional args block is true and timeout is None (the default), block
40+
if necessary until an item is available."""
41+
if block:
42+
# ('queue:test', 'hello world')
43+
item = self.__db.blpop(self.key, timeout=timeout)
44+
else:
45+
# hello world
46+
item = self.__db.lpop(self.key)
47+
48+
if isinstance(item, tuple):
49+
item = item[1]
50+
return item
51+
52+
def get_nowait(self):
53+
"""Equivalent to get(False)."""
54+
return self.get(False)
55+
56+
57+
def test_put():
58+
q = RedisQueue('test')
59+
q.put('hello world')
60+
pass
61+
62+
63+
def test_get():
64+
q = RedisQueue('test')
65+
result = q.get()
66+
print result
67+
68+
69+
def test_get_nowait():
70+
q = RedisQueue('test')
71+
result = q.get_nowait()
72+
print result
73+
74+
75+
def run():
76+
# print sys.argv
77+
try:
78+
if len(sys.argv) > 1:
79+
fun_name = eval(sys.argv[1])
80+
fun_name()
81+
else:
82+
print '缺失参数'
83+
except NameError, e:
84+
print e
85+
print '未定义的方法[%s]' % sys.argv[1]
86+
87+
88+
if __name__ == '__main__':
89+
run()
90+
91+
92+
"""
93+
测试:
94+
95+
✗ python tools/redis_queue.py test_put
96+
97+
✗ python tools/redis_queue.py test_get
98+
hello world/阻塞,不退出
99+
100+
✗ python tools/redis_queue.py test_get_nowait
101+
hello world/None
102+
"""

0 commit comments

Comments
 (0)