初学redis,记录一下简单操作以供以后查找
from pymysql import *
import json
import redis
cache = redis.Redis(host='127.0.0.1', port=6379)
# 1,存字符串
# name='name'
# value='张三'
# cache.setex(name,30,value)
# aa=cache.get(name)
# print(aa.decode())
# 2.删除某个key
# key='user_1'
# cache.delete(key)
# 3,从sql取出,存入redis,并读取
rds = redis.Redis(host='127.0.0.1', port=6379)
conn = connect(host='127.0.0.1', port=3306, user='用户名', passwd='密码', db='数据库', charset='utf8')
cursor = conn.cursor(cursors.DictCursor)
query = cursor.execute("select * from book")
row_all = cursor.fetchall()
for x in row_all:
key=x['id']
value=x
#把id作为key存入redis
rds.setex(key,30,json.dumps(value))
conn.commit()
conn.close()
# 获取redis中所有的key
list_keys = rds.keys()
for key in list_keys:
#字节转字符串
print(key.decode())
#根据key查询value值
a=rds.get(key.decode())
print(json.loads(a.decode()))