核心就是利用pickle将数据序列化,以文字流的方式缓存至redis,要用的时候再取出来进行反序列化。
import redis
from datetime import datetime
from flask import session,request
from ..models import db
import pickle
class Redis:
@staticmethod
def connect():
r = redis.StrictRedis(host='localhost', port=6379, db=0)
return r
#将内存数据二进制通过序列号转为文本流,再存入redis
@staticmethod
def set_data(r,key,data,ex=None):
r.set(key,pickle.dumps(data),ex)
# 将文本流从redis中读取并反序列化,返回返回
@staticmethod
def get_data(r,key):
data = r.get(key)
if data is None:
return None
return pickle.loads(data)
@home.route('/detail/<int:id>')
def detail(id):
today = datetime.now().date()
list_goods = None
# 缓存标记,在页面显示出来
cached_redis_remark = ""
r = Redis.connect()
#商品详情
key = "data-cached:detail-id-%d" % (id)
#从redis读取缓存(不存在的商品不会缓存,因为还是获取得到None)
goods = Redis.get_data(r, key)
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS'] and goods:
# flash("读取缓存数据")
cached_redis_remark += "goods|"
else:
# flash("查询数据库")
goods=Goods.query.get(id)
#将时间转为字符串才能序列化
simple_goods = goods
if goods:
simple_goods.timestamp = str(goods.timestamp)
#缓存入redis
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS']:
# 加入redis缓存,5分钟过期
Redis.set_data(r, key, simple_goods, current_app.config['EXPIRE_CACHED_PAGE_TO_REDIS'])
#推荐商品列表
#推荐数量
recommend_count = 4 if goods else 12
key = "data-cached:detail-recommend-%d" % recommend_count
list_recommend_goods = Redis.get_data(r, key)
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS'] and list_recommend_goods:
# flash("读取缓存数据")
cached_redis_remark += "recommend|"
else:
list_recommend_goods = Goods.query.filter(Goods.coupon_expire >= today).filter_by(effective=True).limit(recommend_count).all()
# 缓存入redis
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS']:
# 加入redis缓存,5分钟过期
Redis.set_data(r, key, list_recommend_goods, current_app.config['EXPIRE_CACHED_PAGE_TO_REDIS'])
return render_template("home/detail.html", goods=goods,list_goods=list_recommend_goods,cached_redis_remark=cached_redis_remark)