一、模块导入
- 安装第三方包redis,然后导入StrictRedis模块
1 2
| from redis import StrictRedis
|
二、创建StrictRedis对象
1 2
| sr = StrictRedis(host='192.168.241.128', port=6379, db=0)
|
三、StrictRedis对象的实例方法
- 根据不同的类型,拥有不同的实例⽅法可以调⽤,与redis命令对应,⽅法需要的参数与命令的参数⼀致
string |
keys |
hash |
list |
set |
zset |
set |
exists |
hset |
lpush |
sadd |
zadd |
setex |
type |
hmset |
rpush |
smembers |
zrange |
mset |
delete |
hkeys |
linsert |
srem |
zrangebyscore |
append |
expire |
hget |
lrange |
|
zscore |
get |
getrange |
hmget |
lset |
|
zrem |
mget |
ttl |
hvals |
lrem |
|
zremrangebyscore |
key |
|
hdel |
|
|
|
四、数据操作
1. 获取键
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from redis import StrictRedis
if __name__=="__main__": try: sr = StrictRedis(host='192.168.241.128', port=6379, db=0) result = sr.keys() print(result) except Exception as e: print(e)
|
2. string
- ⽅法set:添加键、值,如果添加成功则返回True,如果添加失败则返回False
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from redis import StrictRedis
if __name__=="__main__": try: sr = StrictRedis(host='192.168.241.128', port=6379, db=0) result = sr.set('name','zhangsan') print(result) except Exception as e: print(e)
|
- ⽅法get:获取键对应的值,如果键存在则返回对应的值,如果键不存在则返回None
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from redis import StrictRedis
if __name__=="__main__": try: sr = StrictRedis(host='192.168.241.128', port=6379, db=0) result = sr.get('name') print(result) except Exception as e: print(e)
|
- ⽅法set:如果键已经存在则进⾏修改,如果键不存在则进⾏添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from redis import StrictRedis
if __name__=="__main__": try: sr = StrictRedis(host='192.168.241.128', port=6379, db=0) result = sr.set('name','lisi') print(result) except Exception as e: print(e)
|
- ⽅法delete:删除键及对应的值,如果删除成功则返回受影响的键数,否则则返回0
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from redis import StrictRedis
if __name__=="__main__": try: sr = StrictRedis(host='192.168.241.128', port=6379, db=0) result = sr.delete('name') print(result) except Exception as e: print(e)
|
五、连接集群
- 安装第三方包redis-py-cluster,然后导入RedisCluster模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| from rediscluster import RedisCluster if __name__ == '__main__':
startup_nodes = [ {'host': '192.168.241.128', 'port': '7000'}, {'host': '192.168.241.130', 'port': '7001'}, {'host': '192.168.241.128', 'port': '7002'}, ]
try: src=RedisCluster(startup_nodes=startup_nodes) result=src.set('name','anny') print(result) name = src.get('name') print(name) except Exception as e: print(e)
|
附录
https://github.com/Grokzen/redis-py-cluster