2.1 连接
-
方式一
import redis r = redis.Redis(host="127.0.0.1", port=6379)
-
方式二:基于连接池
import redis # 02 基于连接池连接 pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool)
2.2 基本操作
-
字符串操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # ex:过期时间5秒 r.set('key', 'value', ex=5) # nx:不覆盖 r.set('key', 'value2', nx=True) r.setnx('key', 'value3') # 先取值,再设置值 res = r.getset('key', 'value4') # b'value' # 批量 r.mset({'k1': 'v1', 'k2': 'v2'}) res = r.mget(["k1", "k2"]) # [b'v1', b'v2'] # 切片 r.setrange("key", 3, "!!!") # 从指定位置修改 res = r.getrange("key", 0, 5) # 对返回值切片[0:5] # 计算长度 res = r.strlen("key") # 自增,数字或数字字符串 r.set('age', '99') r.incr('age', 2) # b'101' r.decr('age', '4') # b'97' # 追加 r.append('key', 'add') # b'val!!!add'
-
hash操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 赋值 r.hset('h_key', 'k1', 'v1') r.hmset('h_key', {'k2': 'v2', 'k3': 'v3'}) # 弃用警告 # 取值 res = r.hgetall('h_key') # {b'k1': b'v1', b'k2': b'v2', b'k3': b'v3'} res = r.hget('h_key', 'k1') # b'v1' res = r.hmget('h_key', ['k1', 'k2']) # [b'v1', b'v2'] res = r.hkeys('h_key') # [b'k1', b'k2', b'k3'] res = r.hvals('h_key') # [b'v1', b'v2', b'v3'] # 长度 res = r.hlen('h_key') # 是否存在 res = r.hexists('h_key', 'k1') # 删除 r.hdel('h_key', 'k5') # 自增 r.hincrby('h_key', 'age', 2) res = r.hgetall('h_key') # 生成器 res = r.hscan_iter('h_key') for i in r.hscan_iter('h_key'): print(i) # (b'k1', b'v1') ... (b'age', b'24') for i in r.hscan_iter('h_key', match='k*'): print(i) # (b'k1', b'v1') ... (b'k3', b'v3')
-
list操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 赋值 r.lpush('scores', 1, 2, 3) # [b'3', b'2', b'1'] r.rpush('new_scores', 4, 5, 6) # [b'4', b'5', b'6'] # 追加 r.lpushx('scores', 0) r.rpushx('scores', 100) # [b'0', b'3', b'2', b'1', b'100'] # 长度 res = r.llen('scores') # 插入 r.linsert('scores', 'AFTER', '2', '60') # [b'0', b'3', b'2', b'60', b'1', b'100'] # 重新赋值 r.lset('scores', 5, 99) # [b'0', b'3', b'2', b'60', b'1', b'99'] # 删除 r.lrem('scores', count=0, value=99) # [b'0', b'3', b'2', b'60', b'1'],count 0 删除所有、3 删除第3个、-2 删除倒数第2个 res = r.lpop('scores') # [b'3', b'2', b'60', b'1'] res = r.rpop('scores') # [b'3', b'2', b'60'] r.ltrim('scores', 1, 3) # [b'2', b'60'] # 取值 res = r.lindex('scores', 2) # b'60' res = r.lrange('new_scores', 0, -1) res = r.lrange('scores', 0, -1) print(res) r.delete('scores') r.delete('new_scores')
-
set操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 赋值 r.sadd('score_set01', 1, 2, 3, 4, 5, 6, 6) r.sadd('score_set02', 4, 5, 6, 7, 8) # 长度 r.scard('score_set01') r.scard('score_set02') # 交集 r.sinter('score_set01', 'score_set02') # {b'6', b'4', b'5'} # 并集 r.sunion('score_set01', 'score_set02') # {b'7', b'4', b'1', b'2', b'3', b'6', b'5', b'8'} # 差集 r.sdiff('score_set01', 'score_set02') # {b'1', b'2', b'3'} # 判断是否是集合内成员 r.sismember('score_set01', 6) # True r.sismember('score_set01', 7) # False # 随机删除一个,并返回 res = r.spop('score_set01') # b'2' # 删除指定值 r.srem('score_set01', 5) # 随机取3个 res = r.srandmember('score_set01', 3) # [b'2', b'5', b'4'] # 生成器 res = r.sscan_iter('score_set01') for i in r.sscan_iter('score_set01'): print(i) # 取值 res_1 = r.smembers('score_set01') res_2 = r.smembers('score_set02') print(res_1) print(res_2)
-
sortset操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 赋值 r.zadd('z', {'n1': 1, 'n2': 2, 'n3': 5, 'n4': 3}) # 计算长度 r.zcard('z') # 按分数计算长度 r.zcount('z', 1, 3) # 自增:n4分数+4 r.zincrby('z', 4, 'n4') # 按索引取值 res = r.zrange('z', 0, 2) # [b'n1', b'n2', b'n3'] res = r.zrange('z', 0, 3) # [b'n1', b'n2', b'n3', b'n4'] # 查看分数 res = r.zscore('z', 'n4') # 排名(索引) res = r.zrank('z', 'n4') # 删除 r.zrem('z', 'n2') # (0, [(b'n1', 1.0), (b'n3', 5.0), (b'n4', 7.0)]) r.zremrangebyrank('z', 0, 1) # 按排名(索引)删除 (0, [(b'n4', 7.0)]) r.zremrangebyscore('z', 1, 5) # 按分数删除 (0, [(b'n4', 7.0)]) r.zadd('z1', {'n1': 1, 'n2': 2, 'n3': 3, 'x': 100}) r.zadd('z2', {'n3': 4, 'n5': 5, 'n6': 6, 'x': 100}) # 交集:分数默认相加 r.zinterstore('z3', ('z1', 'z2'), aggregate=None) res = r.zscan('z3') # (0, [(b'n3', 7.0), (b'x', 200.0)]) # 并集:取分数最大的 r.zunionstore('z4', ('z1', 'z2'), aggregate='max') res = r.zscan('z4') # (0, [(b'n1', 1.0), (b'n2', 2.0), (b'n5', 5.0), (b'n6', 6.0), (b'n3', 7.0), (b'x', 200.0)]) # 取值 res = r.zscan('z') print(res)
-
其它操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 匹配查键:*任意无穷 ?任意一个 []内部选择 res = r.keys(pattern="k*") # 删除键 res = r.delete("keya") # 是否存在,返回整型 res = r.exists("k1") # 设置过期时间 res = r.expire("k1", 10) # 重命名,找不到会报错 res = r.rename('k2', 'k22') # 随机取一个键 res = r.randomkey() # 查看类型 res = r.type("k2") # 生成器:键 for i in r.scan_iter(match="k*"): print(i) print(res)
-
管道操作
import redis pool = redis.ConnectionPool(host='127.0.0.1', port=6379) r = redis.Redis(connection_pool=pool) # 事物:原子性操作 pipe = r.pipeline(transaction=True) # transaction=True 支持事物 # 原子性操作:保证创建同时成功或同时失败 pipe.set('p_k1', 'p_v1') pipe.set('p_k2', 'p_v2') pipe.execute()
2.3 发布订阅
-
生产者
import redis r = redis.Redis(host='127.0.0.1') r.publish("fm104.5", "hello!")
-
消费者
import redis r = redis.Redis(host='127.0.0.1') pub = r.pubsub() pub.subscribe("fm104.5") pub.parse_response() while 1: msg = pub.parse_response() print(msg) # [b'message', b'fm104.5', b'hello!']