Redis常用来做缓存,对应Python库名为redis;
import json
import redis
# 每个Redis实例都会维护一个自己的连接池,比较耗费开销
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
# 可以直接建立一个连接池,然后作为Redis的参数,就可以实现多个Redis实例共享一个连接池
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
一个例子列举对于字符数据和哈希数据的常用操作;
# 存一个字符数据以便作为哈希数据的key
r.set("local:player:info:totals",'1314')
# 获取对应字符数据
infonum = r.get("local:player:info:totals")
# 数据例子
info = {'player':{'name':'big306','attribute':{'experience':12306,'money':2000,'level':12}}}
# 将例子数据存入对应哈希中
r.hset("local:player:info:data", infonum, json.dumps(info))
# 自增加作为哈希数据key的字符数据
r.incr("local:player:info:totals")
# 分批获取对应哈希中的数据
for item in r.hscan_iter('local:player:info:data'):
print(item)
# 一次性获取对应哈希中全部数据
print(r.hgetall("local:player:info:data"))
# 获取对应哈希中的数据量
print(r.hlen("local:player:info:data"))