
购物车的实现及使用redis存储购物车数据
发布日期:2021-05-04 20:57:46
浏览次数:24
分类:原创文章
本文共 7722 字,大约阅读时间需要 25 分钟。
-
实体类有四个: Product、User、Cart、CartItem
//Product实体类@Data@AllArgsConstructor@NoArgsConstructor@Accessors(chain = true)public class Product implements Serializable { private Integer id; private String productName; private Double price; private String picPath; private String discription;}//User实体类@Data@AllArgsConstructor@NoArgsConstructor@Accessors(chain = true)public class User implements Serializable { private String id; private String username; private String password; private String name; private Integer zip; private String address;}//Cart实体类@Data@AllArgsConstructor@NoArgsConstructor@Accessors(chain = true)public class Cart implements Serializable { private Map<Integer,CartItem> cartMap; private Double totalPrice;}//CartItem实体类@Data@AllArgsConstructor@NoArgsConstructor@Accessors(chain = true)public class CartItem implements Serializable { //书+数量+小计 private Product product; private Integer count; private Double subtotal;}
思路:一个用户对应一个购物车,一个购物车里面有多个购物项
-
引入jedis依赖
<!--引入jedis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <!-- 引入一个工具包 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
-
对应controller中的代码
//购物车展示 @RequestMapping("cart") public String cartShow(Integer id,HttpServletRequest request){ //接受要购买的书的ID 根据书的Id查到这本书 Product product1 = productService.selectOne(id); //将这本书存入购物车 //从session中获取登录者信息 存入redis中的key是userId 值是cart对象 User user = (User) request.getSession().getAttribute("user"); String userId = user.getId(); //从redis中获取购物车信息 Jedis jedis = new Jedis("192.168.174.128",6379); byte[] userIdBs = SerializationUtils.serialize(userId); byte[] sCart = jedis.get(userIdBs); Cart cart = null; //判断购物车是否存在 if(sCart == null){ //购物车不存在,先创建购物车 cart = new Cart(); //全新的购物项内容 CartItem cartItem = new CartItem(product1, 1, product1.getPrice()); //购物车中存的是购物项的集合 String: 书的ID CartItem:购物项 所展示的内容 Map<Integer, CartItem> cartMap = new HashMap<Integer, CartItem>(); cartMap.put(product1.getId(), cartItem); cart.setCartMap(cartMap); cart.setTotalPrice(product1.getPrice()); }else{ //购物车已经存在,反序列化获取这个购物车 cart = SerializationUtils.deserialize(sCart); //判断 当前的商品之前是否买过 购物车的数据在Map集合中 判断 map的key是否存在 if(cart.getCartMap().containsKey(product1.getId())){ //使用key获取已经存在的购物项 直接修改购物项的数量和小计即可 CartItem cartItem = cart.getCartMap().get(product1.getId()); //数量+1 cartItem.setCount(cartItem.getCount()+1); //小计+商品的单价 cartItem.setSubtotal(cartItem.getSubtotal()+product1.getPrice()); // 将修改后的购物项存入购物车的Map中 key 依然是ID value 新的购物项 cart.getCartMap().put(product1.getId(), cartItem); }else{ //没买过 先创建全新的购物项 CartItem cartItem = new CartItem(product1,1,product1.getPrice()); //存入购物车的Map集合 cart.getCartMap().put(product1.getId(), cartItem); } //计算总价格 并set进购物车 double sum = 0.0; Set<Integer> ks = cart.getCartMap().keySet(); Set<Integer> ks1 = cart.getCartMap().keySet(); for (Integer key : ks1) { CartItem item = cart.getCartMap().get(key); sum += (item.getProduct().getPrice())*(item.getCount()); } cart.setTotalPrice(sum); } //将购物车序列化之后存入redis 存入redis中的key是序列化后的userId 值是序列化后的cart对象 byte[] car = SerializationUtils.serialize(cart); byte[] userIDBs = SerializationUtils.serialize(userId); //这个地方要注意不要用 set(String,String) 类型的,要用set(byte[],byte[])类型,否则存进去的类型不对 jedis.set(userIDBs,car); return "redirect:/product/redis"; } //取出redis中的购物车传入前台 @RequestMapping("redis") public String forwardRedis(Model model,HttpServletRequest request){ //获取登录的用户Id User user = (User) request.getSession().getAttribute("user"); String userId = user.getId(); //从redis中获取购物车信息 Jedis jedis = new Jedis("192.168.174.128",6379); byte[] car = jedis.get(SerializationUtils.serialize(userId)); //反序列化重新获取cart对象 if(car != null){ Cart cart = SerializationUtils.deserialize(car); //用model传入前台 model.addAttribute("cart",cart); } return "view/ShopCarView"; } //删除购物车中的书 @RequestMapping("deleteCartBook") public String deleteCartBook(Integer id,HttpServletRequest request) { //获取登录的用户Id User user = (User) request.getSession().getAttribute("user"); String userId = user.getId(); //从redis中获取购物车信息 Jedis jedis = new Jedis("192.168.174.128",6379); byte[] car = jedis.get(SerializationUtils.serialize(userId)); //反序列化重新获取cart对象 Cart cart = SerializationUtils.deserialize(car); Map<Integer, CartItem> cartMap = cart.getCartMap(); //获取要删除的购物项 CartItem cartItem2 = cartMap.get(id); //删除map集合中的键 cartMap.remove(id); //更新总价 cart.setCartMap(cartMap); cart.setTotalPrice(cart.getTotalPrice()-(cartItem2.getProduct().getPrice())*(cartItem2.getCount())); //重新存入redis byte[] deletecar = SerializationUtils.serialize(cart); byte[] userIDBs = SerializationUtils.serialize(userId); //这个地方要注意不要用 set(String,String) 类型的,要用set(byte[],byte[])类型,否则存进去的类型不对 jedis.set(userIDBs,deletecar); return "redirect:/product/redis"; } //清空购物车 @RequestMapping("emptyCar") public String emptyCar(HttpServletRequest request){ //获取登录的用户Id User user = (User) request.getSession().getAttribute("user"); String userId = user.getId(); //从redis中获取购物车信息 Jedis jedis = new Jedis("192.168.174.128",6379); //清空购物车 直接删除redis中对应的key jedis.del(SerializationUtils.serialize(userId)); return "redirect:/product/redis"; } //修改购物项中图书的数量 @RequestMapping("updateCarBookCount") public String updateCartBookCount(Integer id, Integer count,HttpServletRequest request) { if (count > 0) { //获取登录的用户Id User user = (User) request.getSession().getAttribute("user"); String userId = user.getId(); //从redis中获取购物车信息 Jedis jedis = new Jedis("192.168.174.128",6379); byte[] car = jedis.get(SerializationUtils.serialize(userId)); //反序列化重新获取cart对象 Cart cart = SerializationUtils.deserialize(car); Map<Integer, CartItem> cartMap = cart.getCartMap(); //获取要修改图书的购物项 CartItem cartItem = cartMap.get(id); cartItem.setCount(count); cartMap.put(id, cartItem); //更新总价 cart.setCartMap(cartMap); //原总价格 double sum1 = 0.0; //计算总价格 Set<Integer> ks1 = cart.getCartMap().keySet(); for (Integer key : ks1) { CartItem item = cart.getCartMap().get(key); sum1 += (item.getProduct().getPrice()) * (item.getCount()); } cart.setTotalPrice(sum1); //重新存入redis byte[] clearcar = SerializationUtils.serialize(cart); byte[] userIDBs = SerializationUtils.serialize(userId); //这个地方要注意不要用 set(String,String) 类型的,要用set(byte[],byte[])类型,否则存进去的类型不对 jedis.set(userIDBs,clearcar); } return "redirect:/product/redis"; }
发表评论
最新留言
感谢大佬
[***.8.128.20]2025年03月21日 01时06分16秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
4 Java 访问控制符号的范围
2021-05-08
第9章 - 有没有替代原因(检验证据)
2021-05-08
VUE3(八)setup与ref函数
2021-05-08
Vue之Element标签页保留用户操作缓存。
2021-05-08
智能合约开发实践(1)
2021-05-08
2. Spring Boot学习——Yaml等配置文件教程
2021-05-08
MATLAB——操作矩阵的常用函数
2021-05-08
CMake自学记录,看完保证你知道CMake怎么玩!!!
2021-05-08
Eigen库中vector.transpose()函数什么意思
2021-05-08
ORB-SLAM2:LocalMapping线程学习随笔【李哈哈:看看总有收获篇】
2021-05-08
ORB-SLAM2:LoopClosing线程学习随笔【李哈哈:看看总有收获篇】
2021-05-08
牛客练习赛56 D 小翔和泰拉瑞亚(线段树)
2021-05-08
hdu6434 Problem I. Count(数论)(好题)
2021-05-08
NC15553 数学考试(线性DP)
2021-05-08
MySQL隐藏文件.mysql_history风险
2021-05-08
如何通过文件解析MySQL的表结构
2021-05-08
C++的编译过程及原理
2021-05-08