缓存
1 需求背景
缓存是必须的,是为提升性能增加的
标: 减少磁盘数据库的查询,如mysql的查询 ,多的从内存中
读取数据
mysql查询 通常在1s左右 (百毫秒, 0.xxs),1s以上通常认为
是慢查询
redis 持操作的性能 1s可以持1w+ 操作( 可达10W+)
场景
前提: 读取频繁
数据经常变化,基本定会做缓存处
数据可能变化频繁,如果数据是产品的核数据(如评论数
据),可以考虑构建缓存, 缓存时间短,即时缓存5分钟,也能
减少很程度的数据库查询操作,可以提升性能
2 缓存架构
数据存在哪?
多级缓存
本地缓存
全局变保存
orm框架 queryset 查询集(查询结果集) 起到本地缓存的作
django orm
sqlalchemy
外部缓存
可以构建多级
外部存储
redis
memcached
3 缓存数据
保存哪些数据 ? 数据以么形式(类型)保存?
3.1 缓存的数据内容
个数值
机短信验证码
如户的状态数据 user:status -> 0 / 1
数据库记录
以单视图单独考虑,是考虑很多视图可能都会到些公共
数据,就把这些公共的数据缓存,哪个视图到,哪个视图读
取缓存取数据 ,(如户的个信息,章的信息)
较通,缓存个数据可以被多个视图,节省空间
式:
Caching at the object level 缓存数据对象级别
通
Caching at the database query level 缓存数据库查询级别
相缓存数据对象级别 太通,只适于较复杂的查
询,才考虑使
mysql 中有户的个信息表
每条记录 是个户的数据 个数据实体
user:1 -> user_id ,name mobile profile_photo
intro certi
user:20 -> user_id ,name mobile profile_photo
intro certi
1
2
3
4
5
个视图的响应结果
考虑单的视图 ,只只对特定的视图结果进缓存
个
只针对 h5 (html5)
式
sql = 'select * from ..inner join where ...
group by order by limit' -> query_results
hash(sql) -> 'wicwiugfiwuegfwiugiw238'
md5(sql)
缓存
数据名称 数据内容
'wicwiugfiwuegfwiugiw238' -> query_results
使的时候
sql -> md5(sql) -> 'wicwiugfiwuegfwiugiw238'
1
2
3
4
5
6
7
8
9
10
11
@route('/articles')
@cache(exipry=30*60)
def get_articles():
ch = request.args.get('ch')
articles = Article.query.all()
for article in articles:
user =
User.query.filter_by(id=article.user_id).first()
comment =
Comment.query.filter_by(article_id=article.id).all()
results = {...} # 格式化输出
return results
# /articles?ch=123 视图的结果resuls 缓存
# 下次再访问 ‘/articles?ch=123’
1
2
3
4
5
6
7
8
9
10
11
12
13
如果是服务端渲染 (前后端分离)
静态化 算是种缓存式
3.2 缓存数据保存形式
针对的是外部缓存 redis
字符形式
@route('/articles')
@cache(exipry=30*60)
def get_articles():
ch = request.args.get('ch')
articles = Article.query.all()
for article in articles:
user =
User.query.filter_by(id=article.user_id).first
()
comment = Comment.query.all()
results = {...}
return render_template('article_temp',
results)
# redis
# '/artciels?ch=1': html
1
2
3
4
5
6
7
8
9
10
11
12
13
优点: 保存组数据的时候,存储占的空间 相其他类型可能
节省空间
缺点:整存整取 ,如果想获取其中的单字段 是很,需要
整体取出 再序化或反序化, 新某个字段 类似 , 灵活
字符形式
list set hash zset
需要针对特定的数据来选型
优点: 可以针对特定的字段进读写,相对灵活
缺点: 保存组数据的时候,占的空间相字符会稍
user:1 -> user_id ,name mobile profile_photo intro
certi
user1 -> User()对象 -> user1_dict
key value
user:1 -> json.dumps(user1_dict)
pickle.dumps()
json:
1. 只能接受 表 字典 bytes类型
2. json转换成字符 效率速度慢
pickle :
1. 基本持python中的所有类型,(包括定义的类的对象)
2. json转换成字符 效率速度 快
1
2
3
4
5
6
7
8
9
10
11
12
13
user:1 -> user_id ,name mobile profile_photo intro
certi
user1 -> User()对象 -> user1_dict
key value
user:1 -> hash {
name: xxx,
moible: xxx
photo: xxx
}
1
2
3
4
5
6
7
8
9