目标
利用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 Map<String, Object> addCommodity(
- @RequestParam(value = "userId", required = true) String userId,
- @RequestBody List<Map<String, Object>> list
- ) {
- Map<String, Object> map = shoppingCartServer.addCommodity(userId, list);
- return map;
- }
-
- /**
- * 购物车列表
- * http://localhost:8099/shoppingCart/shoppingCartList?userId=001
- *
- * @param userId
- * @return 返回{店铺ID:商品ID=商品数量}的map。
- */
- @GetMapping("/shoppingCartList")
- public Map<Object, Object> shoppingCartList(
- @RequestParam(value = "userId", required = true) String userId,
- @RequestParam(value = "pageNo", defaultValue = "0") Long pageNo,
- @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize
- ) {
- Map<Object, Object> map = shoppingCartServer.shoppingCartList(userId, pageNo, pageSize);
- return map;
- }
-
- /**
- * http://localhost:8099/shoppingCart/updateNum?userId=001&shopId=01&comId=123456&num=342
- * 修改商品数量。
- *
- * @param userId 用户id
- * @param commodityId 商品id
- * @param commodityNum 商品数量
- * @return
- */
- @GetMapping("/updateNum")
- public Map<String, Object> updateNum(
- @RequestParam(value = "userId", required = true) String userId,
- @RequestParam(value = "shopId", required = true) Long shopId,
- @RequestParam(value = "commodityId", required = true) Long commodityId,
- @RequestParam(value = "commodityNum", required = true) Double commodityNum
- ) {
- return shoppingCartServer.updateNum(userId, shopId, commodityId, commodityNum);
- }
-
- /**
- * http://localhost:8099/shoppingCart/delCom?userId=001&shopId=01&comId=123457
- * 删除购物车中的商品
- * @return
- * @param: userId 用户id
- * @param: [{shopId:商铺id,commodityId:商品id},{shopId:商铺id,commodityId:商品id}]
- */
- @PostMapping("/delCommodity")
- public Map<String, Object> delCommodity(
- @RequestParam(value = "userId", required = true) String userId,
- @RequestBody List<Map<String, Object>> list
- ) {
- return shoppingCartServer.delCommodity(userId, list);
- }
- }
业务层
- package com.shoppingcart.service;
-
- import java.util.List;
- import java.util.Map;
-
- public interface ShoppingCartServer {
- //购物车列表
- public Map<Object, Object> shoppingCartList(String userId,Long pageNo,Long pageSize);
- Map<String,Object> updateNum(String userId,Long shopId, Long commodityId, Double commodityNum);
- Map<String, Object> delCommodity(String userId, List<Map<String , Object>> list);
- Map<String, Object> addCommodity(String userId, List<Map<String , Object>> 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 Map<String, Object> addCommodity(String userId, List<Map<String, Object>> list) {
- //记录:list中有哪些商品在购物车中已经存在。
- List<String> 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<String, Object> m = new HashMap<String, Object>() {
- {
- put("existCommoditys", existCommoditys);
- put("existCommoditysMsg", "这些商品在购物车中已经存在,重复数量:"+existCommoditys.size()+"。");
- }
- };
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("data", m);
- map.put("code", 0);
- return map;
- }
-
- //购物车列表
- @Override
- public Map<Object, Object> shoppingCartList(String userId, Long pageNo, Long pageSize) {
- //返回{店铺ID:商品ID=商品数量}的map。
- Map<Object, Object> map = redisService.hmget(SHOPPING_CART + userId);
- return map;
- }
-
- //修改商品数量
- @Override
- public Map<String, Object> updateNum(String userId, Long shopId, Long commodityId, Double commodityNum) {
- Map<String, Object> map = new HashMap<String, Object>();
- //todo 购物车key
- String key = SHOPPING_CART + userId;
- //todo 商品key
- String commodityKey = SHOP_ID + shopId + ":" + commodityId;
- //修改购物车的数量
- boolean boo = redisService.hset(key, commodityKey, commodityNum);
- Map<String, Object> m = new HashMap<String, Object>() {
- {
- 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<String, Object> delCommodity(String userId, List<Map<String, Object>> list) {
- Map<String, Object> map = new HashMap<String, Object>();
- 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 RedisTemplate<String, Object> redisTemplate;
-
- // =============================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<String> 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, value);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 普通缓存放入并设置时间
- *
- * @param key 键
- * @param value 值
- * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
- * @return true成功 false 失败
- */
- public boolean set(String key, Object value, long time) {
- try {
- if (time > 0) {
- redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
- } else {
- set(key, value);
- }
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 递增
- *
- * @param key 键
- * @param delta 要增加几(大于0)
- * @return
- */
- public long incr(String key, long delta) {
- if (delta < 0) {
- throw new RuntimeException("递增因子必须大于0");
- }
- return redisTemplate.opsForValue().increment(key, delta);
- }
-
- /**
- * 递减
- *
- * @param key 键
- * @param delta 要减少几(小于0)
- * @return
- */
- public long decr(String key, long delta) {
- if (delta < 0) {
- throw new RuntimeException("递减因子必须大于0");
- }
- return redisTemplate.opsForValue().increment(key, -delta);
- }
-
- // ================================Hash=================================
-
- /**
- * HashGet
- *
- * @param key 键 不能为null
- * @param item 项 不能为null
- * @return 值
- */
- public Object hget(String key, String item) {
- return redisTemplate.opsForHash().get(key, item);
- }
-
- /**
- * 获取hashKey对应的所有键值
- *
- * @param key 键
- * @return 对应的多个键值
- */
- public Map<Object, Object> hmget(String key) {
- Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
- return entries;
- }
-
- /**
- * HashSet
- *
- * @param key 键
- * @param map 对应多个键值
- * @return true 成功 false 失败
- */
- public boolean hmset(String key, Map<String, Object> map) {
- try {
- redisTemplate.opsForHash().putAll(key, map);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * HashSet 并设置时间
- *
- * @param key 键
- * @param map 对应多个键值
- * @param time 时间(秒)
- * @return true成功 false失败
- */
- public boolean hmset(String key, Map<String, Object> map, long time) {
- try {
- redisTemplate.opsForHash().putAll(key, map);
- if (time > 0) {
- expire(key, time);
- }
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
-
- /**
- * 向一张hash表中放入数据,如果存在就覆盖原来的值。
- *
- * @param key 键
- * @param item 项
- * @param value 值
- * @return true 成功 false失败
- */
- public boolean hset(String key, String item, Object value) {
- try {
- redisTemplate.opsForHash().put(key, item, value);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 向一张hash表中放入数据,如果存在就覆盖原来的值。
- *
- * @param key 键
- * @param item 项
- * @param value 值
- * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
- * @return true 成功 false失败
- */
- public boolean hset(String key, String item, Object value, long time) {
- try {
- redisTemplate.opsForHash().put(key, item, value);
- if (time > 0) {
- expire(key, time);
- }
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 删除hash表中的值
- *
- * @param key 键 不能为null
- * @param item 项 可以使多个 不能为null
- * 返回被删除的数量
- */
- public Long hdel(String key, Object... item) {
- return redisTemplate.opsForHash().delete(key, item);
- }
-
- /**
- * 删除hash表中的值
- *
- * @param key 键 不能为null
- * @param items 项 可以使多个 不能为null
- */
- public void hdel(String key, Collection items) {
- redisTemplate.opsForHash().delete(key, items.toArray());
- }
-
- /**
- * 判断hash表中是否有该项的值
- *
- * @param key 键 不能为null
- * @param item 项 不能为null
- * @return true 存在 false不存在
- */
- public boolean hHasKey(String key, String item) {
- return redisTemplate.opsForHash().hasKey(key, item);
- }
-
- /**
- * hash数据类型:给元素一个增量 如果不存在,就会创建一个 并把新增后的值返回
- *
- * @param key 键
- * @param item 项
- * @param delta 要增加几(大于0)
- * @return
- */
- public double hincr(String key, String item, double delta) {
- return redisTemplate.opsForHash().increment(key, item, delta);
- }
- // ============================set=============================
-
- /**
- * 根据key获取Set中的所有值
- *
- * @param key 键
- * @return
- */
- public Set<Object> sGet(String key) {
- try {
- return redisTemplate.opsForSet().members(key);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 根据value从一个set中查询,是否存在
- *
- * @param key 键
- * @param value 值
- * @return true 存在 false不存在
- */
- public boolean sHasKey(String key, Object value) {
- try {
- return redisTemplate.opsForSet().isMember(key, value);
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 将数据放入set缓存
- *
- * @param key 键
- * @param values 值 可以是多个
- * @return 成功个数
- */
- public long sSet(String key, Object... values) {
- try {
- return redisTemplate.opsForSet().add(key, values);
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- /**
- * 将数据放入set缓存
- *
- * @param key 键
- * @param values 值 可以是多个
- * @return 成功个数
- */
- public long sSet(String key, Collection values) {
- try {
- return redisTemplate.opsForSet().add(key, values.toArray());
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- /**
- * 将set数据放入缓存
- *
- * @param key 键
- * @param time 时间(秒)
- * @param values 值 可以是多个
- * @return 成功个数
- */
- public long sSetAndTime(String key, long time, Object... values) {
- try {
- Long count = redisTemplate.opsForSet().add(key, values);
- if (time > 0)
- expire(key, time);
- return count;
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- /**
- * 获取set缓存的长度
- *
- * @param key 键
- * @return
- */
- public long sGetSetSize(String key) {
- try {
- return redisTemplate.opsForSet().size(key);
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- /**
- * 移除值为value的
- *
- * @param key 键
- * @param values 值 可以是多个
- * @return 移除的个数
- */
- public long setRemove(String key, Object... values) {
- try {
- Long count = redisTemplate.opsForSet().remove(key, values);
- return count;
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- // ===============================list=================================
-
- /**
- * 获取list缓存的内容
- *
- * @param key 键
- * @param start 开始
- * @param end 结束 0 到 -1代表所有值
- * @return
- */
- public List<Object> lGet(String key, long start, long end) {
- try {
- return redisTemplate.opsForList().range(key, start, end);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 获取list缓存的长度
- *
- * @param key 键
- * @return
- */
- public long lGetListSize(String key) {
- try {
- return redisTemplate.opsForList().size(key);
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
-
- /**
- * 通过索引 获取list中的值
- *
- * @param key 键
- * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
- * @return
- */
- public Object lGetIndex(String key, long index) {
- try {
- return redisTemplate.opsForList().index(key, index);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 将list放入缓存
- *
- * @param key 键
- * @param value 值
- * @return
- */
- public boolean lSet(String key, Object value) {
- try {
- redisTemplate.opsForList().rightPush(key, value);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 将list放入缓存
- *
- * @param key 键
- * @param value 值
- * @param time 时间(秒)
- * @return
- */
- public boolean lSet(String key, Object value, long time) {
- try {
- redisTemplate.opsForList().rightPush(key, value);
- if (time > 0)
- expire(key, time);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 将list放入缓存
- *
- * @param key 键
- * @param value 值
- * @return
- */
- public boolean lSet(String key, List<Object> value) {
- try {
- redisTemplate.opsForList().rightPushAll(key, value);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 将list放入缓存
- *
- * @param key 键
- * @param value 值
- * @param time 时间(秒)
- * @return
- */
- public boolean lSet(String key, List<Object> value, long time) {
- try {
- redisTemplate.opsForList().rightPushAll(key, value);
- if (time > 0)
- expire(key, time);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 根据索引修改list中的某条数据
- *
- * @param key 键
- * @param index 索引
- * @param value 值
- * @return
- */
- public boolean lUpdateIndex(String key, long index, Object value) {
- try {
- redisTemplate.opsForList().set(key, index, value);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 移除N个值为value
- *
- * @param key 键
- * @param count 移除多少个
- * @param value 值
- * @return 移除的个数
- */
- public long lRemove(String key, long count, Object value) {
- try {
- Long remove = redisTemplate.opsForList().remove(key, count, value);
- return remove;
- } catch (Exception e) {
- e.printStackTrace();
- return 0;
- }
- }
- // ===============================Zset=================================
-
- /**
- * 给key键的value增加value分数,没有则会创建。
- *
- * @param key 键
- * @param value 值
- * @param score 分数
- */
- public Double incrementScore(String key, String value, double score) {
- //Boolean add = redisTemplate.boundZSetOps(key).add(value, score);
- Double add = redisTemplate.boundZSetOps(key).incrementScore(value, score);
- return add;
- }
-
- /**
- * 获得指定Zset元素的分数
- *
- * @param key
- * @param value
- * @return
- */
- public Double score(String key, String value) {
- Double score = redisTemplate.boundZSetOps(key).score(value);
- return score;
- }
-
- /**
- * 升序查询key集合内[endTop,startTop]如果是负数表示倒数
- * endTop=-1,startTop=0表示获取所有数据。
- *
- * @param key
- * @param startPage
- * @param endPage
- */
- public Set<ZSetOperations.TypedTuple<Object>> rangeWithScores(String key, int startPage, int endPage) {
- Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.boundZSetOps(key).rangeWithScores(startPage, endPage);
- return set;
- }
-
- /**
- * 降序查询key集合内[endTop,startTop],如果是负数表示倒数
- * endTop=-1,startTop=0表示获取所有数据。
- *
- * @param key
- * @param startPage
- * @param endPage
- */
- public Set<ZSetOperations.TypedTuple<Object>> reverseRangeWithScores(String key, int startPage, int endPage) {
- Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.boundZSetOps(key).reverseRangeWithScores(startPage, endPage);
- return set;
- }
-
- /**
- * 批量新增数据
- *
- * @param key
- * @param set
- * @return
- */
- public Long zsetAdd(String key, Set set) {
- Long add = redisTemplate.boundZSetOps(key).add(set);
- return add;
- }
-
- /**
- * 删除指定键的指定下标范围数据
- *
- * @param key
- * @param startPage
- * @param endPage
- */
- public Long zsetRemoveRange(String key, int startPage, int endPage) {
- Long l = redisTemplate.boundZSetOps(key).removeRange(startPage, endPage);
- return l;
- }
- /**
- * 删除指定键的指定值
- *
- * @param key
- * @param value
- */
- public Long zsetRemove(String key, String value) {
- Long remove = redisTemplate.boundZSetOps(key).remove(value);
- return remove;
- }
- }
到此这篇关于Redis实战之商城购物车功能的实现代码的文章就介绍到这了,更多相关Redis商城购物车内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!