Redis-Py 使用
(1) 导入依赖库:
import redis
(2) 生成客户端连接:需要Redis的实例IP和端口两个参数:
client = redis.StrictRedis(host=’127.0.0.1′, port=6379)
(3) 设置和获取键值
client.set(key, "python-redis")
client.get(key)
(4) 数据类型API
# string
client.set("hello", "world")
# 输出结果: True
client.get("hello")
# 输出结果: world
client.incr("counter")
# 输出结果: 1
# hash
client.hset("myhash", "f1", "v1")
client.hget("myhash", "f2", "v2")
# 输出结果: {'f1': 'v1', 'f2': 'v2'}
client.hgetall("myhash")
# list
client.rpush("mylist", 1)
client.rpush("mylist", 2)
client.rpush("mylist", 2)
# 输出结果: ['1', '2', '3']
client.lrange("mylist", 0, -1)
# set
client.sadd("myset", "a")
client.sadd("myset", "b")
client.sadd("myset", "a")
# 输出结果: set(['a', 'b'])
chient.smembers("myset")
# zset
client.zadd("myzset", "99", "tom")
client.zadd("myzset", "66", "peter")
client.zadd("myzset", "33", "james")
# 输出结果: [('james', 33.0), ('peter', 66.0), ('tom', 99.0)]
client.zrange("myzset", 0, -1, withscores=True)