博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python redis 分页
阅读量:6995 次
发布时间:2019-06-27

本文共 1542 字,大约阅读时间需要 5 分钟。

hot3.png

使用SortedSet 和 Hash 进行分页处理

import jsonfrom redis import ConnectionPool, StrictRedisimport time, datetimepool = 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': '数学课'}]

 

转载于:https://my.oschina.net/xiaohuai4869/blog/3012780

你可能感兴趣的文章