文章目录
1,缓存粒度和缓存数据类型
-
缓存粒度
- 如何选择要缓存的数据类型,缓存什么样的数据
-
缓存数据类型介绍
-
一个数值
- 短信验证码
- 用户状态
- 用户状态是否可用
- key user:{user_id}:enable
- value:1 or 0
-
数据库记录
-
一组数据
- 用户的个人信息
- key: user:{user_id}:profile
- value:json.dumps(dict)
-
联合 查询的结果(针对经常的复杂的联合查询结果进行缓存)
- 以sql语句hash结果作为key
- 查询结果作为value
query_result = User.query.join(User.profile).filter_by(id=1).first() -> sql = "select a.user_id, a.user_name, b.gender, b.birthday from tbl_user as a inner join tbl_profile as b on a.user_id=b.user_id where a.user_id=1;" # hash算法 md5 query = md5(sql) # 'fwoifhwoiehfiowy23982f92h929y3209hf209fh2' # redis 写入数据并设置过期时间;使用的时候按sql取指纹 按指纹去redis取结果 没有结果再查库 setex(query, expiry, json.dumps(query_result))
-
-
视图函数返回的结果
- key: url
- value: json.dumps(view_func_results)
-
页面
- key: url
- value: html
-
-
选择的缓存数据类型
- 根据具体的业务实际情况选择缓存数据的类型
-
缓存数据的保存方式(缓存数据所采用的的数据结构)
-
序列化字符串json
优点:存储字符串节省空间
缺点:序列化有时间开销;更新不方便(直接删除)
-
redis其他数据结构类型
memcached只能选择把数据缓存成字符串,redis多种多样
优点:读写不需要序列化转换;可以更新内部数据
缺点:相比字符串,采用复合结构存储空间占用大
-