1.连接redis(两种方式)
-
1 # decode_responses=True: 解决获取的值类型是bytes字节问题 2 r = redis.Redis(host=‘localhost‘, port=‘6379‘, db=0, decode_responses=True)
-
1 pool = redis.ConnectionPool(host=‘localhost‘, port=6379, db=0, decode_responses=True) 2 r = redis.Redis(connection_pool=pool)
2.字符串类型 String
1 # ex过期时间 单位秒S 2 r.set(‘name‘, ‘Jack‘, ex=20) 3 rst = r.get(‘name‘) 4 print(rst) 5 6 7 结果: "Jack"
3.列表类型 list
1 r.lpush(‘object‘, ‘one‘) 2 r.lpush(‘object‘, ‘two‘) 3 r.lpush(‘object‘, ‘three‘) 4 r.lpush(‘object‘, ‘four‘) 5 r.lpush(‘object‘, ‘five‘) 6 r.lpush(‘object‘, ‘six‘) 7 ret = r.lrange(‘object‘, 0, 5) 8 print(ret[::-1], len(ret)) 9 10 11 结果: [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘, ‘six‘] 6
4.哈希类型 hash
1 r.hset(‘user:info‘, ‘name‘, ‘Jack‘) 2 r.hset(‘user:info‘, ‘age‘, 20) 3 r.hset(‘user:info‘, ‘phone‘, ‘18712909999‘) 4 r.hset(‘user:info‘, ‘email‘, ‘[email protected]‘) 5 rst = r.hgetall(‘user:info‘) 6 print(rst) 7 8 9 结果: {‘age‘: ‘20‘, ‘email‘: ‘[email protected]‘, ‘name‘: ‘Jack‘, ‘phone‘: ‘18712909999‘}
5.集合类型 set
1 r.sadd(‘set‘, ‘one‘) 2 r.sadd(‘set‘, ‘two‘) 3 r.sadd(‘set‘, ‘three‘) 4 res = r.smembers(‘set‘) 5 print(res) 6 7 8 结果: {‘two‘, ‘one‘, ‘three‘}
6.有序集合类型 sorted set
1 r.zadd(‘mark‘, ‘one‘, 1) 2 r.zadd(‘mark‘, ‘two‘, 2) 3 r.zadd(‘mark‘, ‘three‘, 3) 4 r.zadd(‘mark‘, ‘four‘, 4) 5 r.zadd(‘mark‘, ‘five‘, 5) 6 result = r.zrange(‘mark‘, 0, 10) 7 print(result) 8 9 10 结果: [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘]
时间: 2024-12-28 11:58:45