使用redis存储历史浏览记录
核心是分析流程
1.什么时候需要添加历史浏览记录?
访问具体商品详情页面时
2.什么时候需要获取历史浏览记录?
根据具体情况而定
3.存储在哪?
redis数据库,如果使用普通的关系型数据库,经常对数据库进行读写,效率比redis低得多
4.历史浏览记录的存储格式?
这里设计一个用户存储一条记录,使用list存储
history_用户id : [SKUid1, SKUid2,…]
新增一条历史浏览记录 具体代码
conn = get_redis_connection('default')
history = 'history_%s' % user.id # 拼接出key
conn.lrem(history, 0, goods_id) # 每次插入前都删除以前的历史记录,
conn.lpush(history, goods_id) # 从左侧插入
conn.ltrim(history, 0, 4) # 只保留5条数据
获取历史浏览记录代码
conn = get_redis_connection('default')
history = 'history_%s' % user.id
goods_id = conn.lrange(history, 0 ,4) # 只取前五个数据,存放商品id
goods_res = list()
for id in goods_id: # 按顺序插入
goods = GoodsSKU.objects.get(id=id)
goods_res.append(goods)