您现在的位置是:网站首页> 编程资料编程资料
Redis实战之商城购物车功能的实现代码_Redis_
2023-05-27
470人已围观
简介 Redis实战之商城购物车功能的实现代码_Redis_
目标
利用Redis实现商城购物车功能。
功能
根据用户编号查询购物车列表,且各个商品需要跟在对应的店铺下;统计购物车中的商品总数;新增或删减购物车商品;增加或减少购物车中的商品数量。
分析
Hash数据类型:值为多组映射,相当于JAVA中的Map。适合存储对象数据类型。因为用户ID作为唯一的身份标识,所以可以把模块名称+用户ID作为Redis的键;商品ID作为商品的唯一标识,可以把店铺编号+商品ID作为Hash元素的键,商品数量为元素的值。
代码实现
控制层
package com.shoppingcart.controller; import com.shoppingcart.service.ShoppingCartServer; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * redis实现购物车功能 */ @RestController @RequestMapping("/shoppingCart") public class ShoppingCartController { @Resource private ShoppingCartServer shoppingCartServer; /** * http://localhost:8099/shoppingCart/addCommodity?userId=001&shopId=1234560&commodityId=001&commodityNum=336 * 添加商品 * @return * @param: userId 用户ID * @param: [{shopId:商铺id,commodityId:商品id,commodityNum:商品数量},{shopId:商铺id,commodityId:商品id,commodityNum:商品数量}] * 测试数据: [ { "shopId": 123, "commodityId": 145350, "commodityNum": 155.88 }, { "shopId": 123, "commodityId": 6754434, "commodityNum": 945.09 }, { "shopId": 123, "commodityId": 7452, "commodityNum": 2445.09 }, { "shopId": 3210, "commodityId": 98766, "commodityNum": 2345.09 }, { "shopId": 456, "commodityId": 2435640, "commodityNum": 11945.09 } ] */ @GetMapping("/addCommodity") public MapaddCommodity( @RequestParam(value = "userId", required = true) String userId, @RequestBody List
业务层
package com.shoppingcart.service; import java.util.List; import java.util.Map; public interface ShoppingCartServer { //购物车列表 public MapshoppingCartList(String userId,Long pageNo,Long pageSize); Map updateNum(String userId,Long shopId, Long commodityId, Double commodityNum); Map delCommodity(String userId, List
package com.shoppingcart.service.impl; import com.shoppingcart.service.ShoppingCartServer; import com.shoppingcart.utils.RedisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class ShoppingCartServerImpl implements ShoppingCartServer { @Autowired private RedisService redisService; //购物车键名前缀 public static final String SHOPPING_CART = "shoppingCart:"; //购物车的元素键名前缀 public static final String SHOP_ID = "shopId"; //添加商品 @Override public MapaddCommodity(String userId, List > list) { //记录:list中有哪些商品在购物车中已经存在。 List existCommoditys = new ArrayList<>(); //todo 购物车key String key = SHOPPING_CART + userId; for (int i = 0; i < list.size(); i++) { String commodityKey = SHOP_ID + list.get(i).get("shopId") + ":" + list.get(i).get("commodityId"); //todo 添加商品 boolean boo = redisService.hsetnx(key, commodityKey, Double.parseDouble(list.get(i).get("commodityNum") + "")); if (!boo) { existCommoditys.add(commodityKey); } } Map m = new HashMap () { { put("existCommoditys", existCommoditys); put("existCommoditysMsg", "这些商品在购物车中已经存在,重复数量:"+existCommoditys.size()+"。"); } }; Map map = new HashMap (); map.put("data", m); map.put("code", 0); return map; } //购物车列表 @Override public Map shoppingCartList(String userId, Long pageNo, Long pageSize) { //返回{店铺ID:商品ID=商品数量}的map。 Map map = redisService.hmget(SHOPPING_CART + userId); return map; } //修改商品数量 @Override public Map updateNum(String userId, Long shopId, Long commodityId, Double commodityNum) { Map map = new HashMap (); //todo 购物车key String key = SHOPPING_CART + userId; //todo 商品key String commodityKey = SHOP_ID + shopId + ":" + commodityId; //修改购物车的数量 boolean boo = redisService.hset(key, commodityKey, commodityNum); Map m = new HashMap () { { put("key", key); put("commodityKey", commodityKey); put("commodityNum", commodityNum); } }; map.put("data", m); map.put("msg", boo == true ? "修改购物车商品数量成功。" : "修改购物车商品数量失败。"); map.put("code", boo == true ? 0 : 1); return map; } //删除商品 @Override public Map delCommodity(String userId, List > list) { Map map = new HashMap (); String[] commodityIds = new String[list.size()]; for (int i = 0; i < list.size(); i++) { //todo 商品key commodityIds[i] = SHOP_ID + list.get(i).get("shopId") + ":" + list.get(i).get("commodityId"); } //todo 购物车key String key = SHOPPING_CART + userId; //删除商品的数量 Long num = redisService.hdel(key, commodityIds); map.put("msg", "删除购物车的商品数量:" + num); map.put("code", 0); return map; } }
工具类
package com.shoppingcart.utils; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { // 日期转字符串,返回指定的格式 public static String dateToString(Date date, String dateFormat) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(date); } }
package com.shoppingcart.utils; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisZSetCommands; import org.springframework.data.redis.connection.SortParameters; import org.springframework.data.redis.core.DefaultTypedTuple; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.w3c.dom.ranges.Range; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Service public class RedisService { @Autowired private RedisTemplateredisTemplate; // =============================common============================ /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { List list = new ArrayList<>(Arrays.asList(key)); redisTemplate.delete(list); } } } /** * 删除缓存 * * @param keys 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(Collection keys) { if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(keys)) { redisTemplate.delete(keys); } } // ============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key,
相关内容
- 利用redis实现分布式锁,快速解决高并发时的线程安全问题_Redis_
- Redis和数据库 数据同步问题的解决_Redis_
- Redis 实现同步锁案例_Redis_
- 同一份数据Redis为什么要存两次_Redis_
- Redis实现分布式Session管理的机制详解_Redis_
- kubernetes环境部署单节点redis数据库的方法_Redis_
- 银河麒麟V10sp1服务器系统安装redis不能使用的快速解决办法_Redis_
- Redis6.0搭建集群Redis-cluster的方法_Redis_
- 浅谈Redis存储数据类型及存取值方法_Redis_
- 基于Redis过期事件实现订单超时取消_Redis_
点击排行
本栏推荐
