既然是消息列队,那肯定会借助到Redis数据结构中的list
list 这个数据类型,在python里是一个列表,在redis里就是一个有序队列(或者说数据链表)了。
类型图示如下:
通过这个结构就可以对list很清楚了,我们可以利用list的数据接口模式,设计从左端和右端都可以对list进元素的同向处理(满足队列的特性先到先出)。
1、从左端插入元素
from redis import StrictRedis
redis = StrictRedis(host='localhost',port=6379,password='')
redis.lpush('testList',1,2,3,4)
print(redis.lrange('testList',0,3))
打印输出内容,如下:
[b'4', b'3', b'2', b'1']
类似的从左测插入的方法还有lpushx(name,value),区别只有当name存在才将value插入到最左边。
2、从右边插入元素
from redis import StrictRedis
redis = StrictRedis(host='localhost',port=6379,password='')
# redis.lpush('testList',1,2,3,4)
redis.rpush('testList',5)
print(redis.lrange('testList',0,4))
结果:
[b'4', b'3', b'2', b'1', b'5']
3、从左边取出元素怎么取呢?
from redis import StrictRedis
redis = StrictRedis(host='localhost',port=6379,password='')
# redis.lpush('testList',1,2,3,4)
# redis.rpush('testList',5)
print(redis.lpop('testList'))
print(redis.lpop('testList'))
print(redis.lrange('testList',0,4))
结果:
b'4'
b'3'
[b'2', b'1', b'5']
我们会看到从左侧已经取出了两个元素了。剩下来[b’2’, b’1’, b’5’]
4、从右侧呢?
当然就是rc.rpop()了
python对于redis的基础使用和Redis作为队列的使用就介绍这些。