核心就是利用pickle將數(shù)據(jù)序列化胡桨,以文字流的方式緩存至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
#將內存數(shù)據(jù)二進制通過序列號轉為文本流炭剪,再存入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("讀取緩存數(shù)據(jù)")
cached_redis_remark += "goods|"
else:
# flash("查詢數(shù)據(jù)庫")
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'])
#推薦商品列表
#推薦數(shù)量
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("讀取緩存數(shù)據(jù)")
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)