使用SortedSet 和 Hash 进行分页处理
import json
from redis import ConnectionPool, StrictRedis
import time, datetime
pool = ConnectionPool(host='192.168.2.122', port=6379, db=0)
# 由于redis输出数据类型是bytes,所以连接配置提供decode_responses选项,可以选择直接输出str类型数据
redis = StrictRedis(connection_pool=pool, decode_responses=True)
if __name__ == '__main__':
# redis 的SortedSet 是通过分数来排序的
# 分数 用 时间戳来代替
t = time.time()
redis.zadd('subject', {'Chinese': t})
# 将内容存储到 Hash
dic = {
'subject': 'Chinese',
'ins': "语文课",
}
dump = json.dumps(dic)
redis.hset("subject_ins", "Chinese", dump)
t = time.time()
redis.zadd('subject', {'Math': t})
dic = {
'subject': 'Math',
'ins': "数学课",
}
dump = json.dumps(dic)
redis.hset("subject_ins", "Math", dump)
t = time.time()
redis.zadd('subject', {'Physics': t})
dic = {
'subject': 'Physics',
'ins': "物理课",
}
dump = json.dumps(dic)
redis.hset("subject_ins", "Physics", dump)
zrange = redis.zrange('subject', 0, 1, desc=False, withscores=True)
print(zrange)
zrange = list(map(lambda x: str(x[0], encoding='utf-8'), zrange))
# 按排序 获取subject
print(zrange)
# 获取hash
subject_ins = redis.hmget('subject_ins', zrange)
subject_ins = list(map(lambda x: json.loads(str(x, encoding='utf-8')), subject_ins))
print(subject_ins)
结果
[(b'Chinese', 1550712359.4595), (b'Math', 1550712359.464)]
['Chinese', 'Math']
[{'subject': 'Chinese', 'ins': '语文课'}, {'subject': 'Math', 'ins': '数学课'}]