图片截自:https://www.bilibili.com/video/BV1np4y1C7Yf?p=237
对于购物车:
我们存储再redis中的数据类似于Java中Map<String,Map<String,String>>形式,将外层Map的key记为K,内层Map的key和value分别记为HK、HV
- 使用K来存储用户标识(例如:用户的ID)
- 使用HK存储商品标识(例如:商品ID)
- 使用HV存储购物车商品信息(例如:购物车中商品的数目,是否选中等等)
对于购物车商品的操作:
stringRedisTemplate:
org.springframework.data.redis.core.StringRedisTemplate
key:要保存商品的标识;
value:要存储商品的详细信息;
userId:用户标识
operations:内层的Map;BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(userId);
- 增加商品:
operations.put(key,value);
- 删除商品:
operations.delete(key);
- 修改商品:
operations.put(key);
(覆盖,如果需要原数据中的内容,可先查询数据,修改后再覆盖) - 查询商品:
operations.get(key);
- 清空某用户购物车:
stringRedisTemplate.delete(userId);