经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
Redis实战之商城购物车功能的实现代码
来源:jb51  时间:2021/2/1 11:30:31  对本文有异议

目标

利用Redis实现商城购物车功能。

功能

根据用户编号查询购物车列表,且各个商品需要跟在对应的店铺下;统计购物车中的商品总数;新增或删减购物车商品;增加或减少购物车中的商品数量。


分析

Hash数据类型:值为多组映射,相当于JAVA中的Map。适合存储对象数据类型。因为用户ID作为唯一的身份标识,所以可以把模块名称+用户ID作为Redis的键;商品ID作为商品的唯一标识,可以把店铺编号+商品ID作为Hash元素的键,商品数量为元素的值。


代码实现

控制层

  1. package com.shoppingcart.controller;
  2. import com.shoppingcart.service.ShoppingCartServer;
  3. import org.springframework.web.bind.annotation.*;
  4. import javax.annotation.Resource;
  5. import java.util.List;
  6. import java.util.Map;
  7. /**
  8. * redis实现购物车功能
  9. */
  10. @RestController
  11. @RequestMapping("/shoppingCart")
  12. public class ShoppingCartController {
  13. @Resource
  14. private ShoppingCartServer shoppingCartServer;
  15. /**
  16. * http://localhost:8099/shoppingCart/addCommodity?userId=001&shopId=1234560&commodityId=001&commodityNum=336
  17. * 添加商品
  18. * @return
  19. * @param: userId 用户ID
  20. * @param: [{shopId:商铺id,commodityId:商品id,commodityNum:商品数量},{shopId:商铺id,commodityId:商品id,commodityNum:商品数量}]
  21. * 测试数据:
  22. [
  23. {
  24. "shopId": 123,
  25. "commodityId": 145350,
  26. "commodityNum": 155.88
  27. },
  28. {
  29. "shopId": 123,
  30. "commodityId": 6754434,
  31. "commodityNum": 945.09
  32. },
  33. {
  34. "shopId": 123,
  35. "commodityId": 7452,
  36. "commodityNum": 2445.09
  37. },
  38. {
  39. "shopId": 3210,
  40. "commodityId": 98766,
  41. "commodityNum": 2345.09
  42. },
  43. {
  44. "shopId": 456,
  45. "commodityId": 2435640,
  46. "commodityNum": 11945.09
  47. }
  48. ]
  49. */
  50. @GetMapping("/addCommodity")
  51. public Map<String, Object> addCommodity(
  52. @RequestParam(value = "userId", required = true) String userId,
  53. @RequestBody List<Map<String, Object>> list
  54. ) {
  55. Map<String, Object> map = shoppingCartServer.addCommodity(userId, list);
  56. return map;
  57. }
  58. /**
  59. * 购物车列表
  60. * http://localhost:8099/shoppingCart/shoppingCartList?userId=001
  61. *
  62. * @param userId
  63. * @return 返回{店铺ID:商品ID=商品数量}的map。
  64. */
  65. @GetMapping("/shoppingCartList")
  66. public Map<Object, Object> shoppingCartList(
  67. @RequestParam(value = "userId", required = true) String userId,
  68. @RequestParam(value = "pageNo", defaultValue = "0") Long pageNo,
  69. @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize
  70. ) {
  71. Map<Object, Object> map = shoppingCartServer.shoppingCartList(userId, pageNo, pageSize);
  72. return map;
  73. }
  74. /**
  75. * http://localhost:8099/shoppingCart/updateNum?userId=001&shopId=01&comId=123456&num=342
  76. * 修改商品数量。
  77. *
  78. * @param userId 用户id
  79. * @param commodityId 商品id
  80. * @param commodityNum 商品数量
  81. * @return
  82. */
  83. @GetMapping("/updateNum")
  84. public Map<String, Object> updateNum(
  85. @RequestParam(value = "userId", required = true) String userId,
  86. @RequestParam(value = "shopId", required = true) Long shopId,
  87. @RequestParam(value = "commodityId", required = true) Long commodityId,
  88. @RequestParam(value = "commodityNum", required = true) Double commodityNum
  89. ) {
  90. return shoppingCartServer.updateNum(userId, shopId, commodityId, commodityNum);
  91. }
  92. /**
  93. * http://localhost:8099/shoppingCart/delCom?userId=001&shopId=01&comId=123457
  94. * 删除购物车中的商品
  95. * @return
  96. * @param: userId 用户id
  97. * @param: [{shopId:商铺id,commodityId:商品id},{shopId:商铺id,commodityId:商品id}]
  98. */
  99. @PostMapping("/delCommodity")
  100. public Map<String, Object> delCommodity(
  101. @RequestParam(value = "userId", required = true) String userId,
  102. @RequestBody List<Map<String, Object>> list
  103. ) {
  104. return shoppingCartServer.delCommodity(userId, list);
  105. }
  106. }

业务层

  1. package com.shoppingcart.service;
  2. import java.util.List;
  3. import java.util.Map;
  4. public interface ShoppingCartServer {
  5. //购物车列表
  6. public Map<Object, Object> shoppingCartList(String userId,Long pageNo,Long pageSize);
  7. Map<String,Object> updateNum(String userId,Long shopId, Long commodityId, Double commodityNum);
  8. Map<String, Object> delCommodity(String userId, List<Map<String , Object>> list);
  9. Map<String, Object> addCommodity(String userId, List<Map<String , Object>> list);
  10. }
  1. package com.shoppingcart.service.impl;
  2. import com.shoppingcart.service.ShoppingCartServer;
  3. import com.shoppingcart.utils.RedisService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. @Service
  11. public class ShoppingCartServerImpl implements ShoppingCartServer {
  12. @Autowired
  13. private RedisService redisService;
  14. //购物车键名前缀
  15. public static final String SHOPPING_CART = "shoppingCart:";
  16. //购物车的元素键名前缀
  17. public static final String SHOP_ID = "shopId";
  18. //添加商品
  19. @Override
  20. public Map<String, Object> addCommodity(String userId, List<Map<String, Object>> list) {
  21. //记录:list中有哪些商品在购物车中已经存在。
  22. List<String> existCommoditys = new ArrayList<>();
  23. //todo 购物车key
  24. String key = SHOPPING_CART + userId;
  25. for (int i = 0; i < list.size(); i++) {
  26. String commodityKey = SHOP_ID + list.get(i).get("shopId") + ":" + list.get(i).get("commodityId");
  27. //todo 添加商品
  28. boolean boo = redisService.hsetnx(key, commodityKey, Double.parseDouble(list.get(i).get("commodityNum") + ""));
  29. if (!boo) {
  30. existCommoditys.add(commodityKey);
  31. }
  32. }
  33. Map<String, Object> m = new HashMap<String, Object>() {
  34. {
  35. put("existCommoditys", existCommoditys);
  36. put("existCommoditysMsg", "这些商品在购物车中已经存在,重复数量:"+existCommoditys.size()+"。");
  37. }
  38. };
  39. Map<String, Object> map = new HashMap<String, Object>();
  40. map.put("data", m);
  41. map.put("code", 0);
  42. return map;
  43. }
  44. //购物车列表
  45. @Override
  46. public Map<Object, Object> shoppingCartList(String userId, Long pageNo, Long pageSize) {
  47. //返回{店铺ID:商品ID=商品数量}的map。
  48. Map<Object, Object> map = redisService.hmget(SHOPPING_CART + userId);
  49. return map;
  50. }
  51. //修改商品数量
  52. @Override
  53. public Map<String, Object> updateNum(String userId, Long shopId, Long commodityId, Double commodityNum) {
  54. Map<String, Object> map = new HashMap<String, Object>();
  55. //todo 购物车key
  56. String key = SHOPPING_CART + userId;
  57. //todo 商品key
  58. String commodityKey = SHOP_ID + shopId + ":" + commodityId;
  59. //修改购物车的数量
  60. boolean boo = redisService.hset(key, commodityKey, commodityNum);
  61. Map<String, Object> m = new HashMap<String, Object>() {
  62. {
  63. put("key", key);
  64. put("commodityKey", commodityKey);
  65. put("commodityNum", commodityNum);
  66. }
  67. };
  68. map.put("data", m);
  69. map.put("msg", boo == true ? "修改购物车商品数量成功。" : "修改购物车商品数量失败。");
  70. map.put("code", boo == true ? 0 : 1);
  71. return map;
  72. }
  73. //删除商品
  74. @Override
  75. public Map<String, Object> delCommodity(String userId, List<Map<String, Object>> list) {
  76. Map<String, Object> map = new HashMap<String, Object>();
  77. String[] commodityIds = new String[list.size()];
  78. for (int i = 0; i < list.size(); i++) {
  79. //todo 商品key
  80. commodityIds[i] = SHOP_ID + list.get(i).get("shopId") + ":" + list.get(i).get("commodityId");
  81. }
  82. //todo 购物车key
  83. String key = SHOPPING_CART + userId;
  84. //删除商品的数量
  85. Long num = redisService.hdel(key, commodityIds);
  86. map.put("msg", "删除购物车的商品数量:" + num);
  87. map.put("code", 0);
  88. return map;
  89. }
  90. }

 

工具类

  1. package com.shoppingcart.utils;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class DateUtils {
  5. // 日期转字符串,返回指定的格式
  6. public static String dateToString(Date date, String dateFormat) {
  7. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  8. return sdf.format(date);
  9. }
  10. }
  1. package com.shoppingcart.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.connection.RedisZSetCommands;
  5. import org.springframework.data.redis.connection.SortParameters;
  6. import org.springframework.data.redis.core.DefaultTypedTuple;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.data.redis.core.ZSetOperations;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.util.CollectionUtils;
  11. import org.w3c.dom.ranges.Range;
  12. import java.util.*;
  13. import java.util.concurrent.TimeUnit;
  14. import java.util.stream.Collectors;
  15. @Service
  16. public class RedisService {
  17. @Autowired
  18. private RedisTemplate<String, Object> redisTemplate;
  19. // =============================common============================
  20. /**
  21. * 指定缓存失效时间
  22. *
  23. * @param key 键
  24. * @param time 时间(秒)
  25. * @return
  26. */
  27. public boolean expire(String key, long time) {
  28. try {
  29. if (time > 0) {
  30. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  31. }
  32. return true;
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. return false;
  36. }
  37. }
  38. /**
  39. * 根据key 获取过期时间
  40. *
  41. * @param key 键 不能为null
  42. * @return 时间(秒) 返回0代表为永久有效
  43. */
  44. public long getExpire(String key) {
  45. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  46. }
  47. /**
  48. * 判断key是否存在
  49. *
  50. * @param key 键
  51. * @return true 存在 false不存在
  52. */
  53. public boolean hasKey(String key) {
  54. try {
  55. return redisTemplate.hasKey(key);
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. return false;
  59. }
  60. }
  61. /**
  62. * 删除缓存
  63. *
  64. * @param key 可以传一个值 或多个
  65. */
  66. @SuppressWarnings("unchecked")
  67. public void del(String... key) {
  68. if (key != null && key.length > 0) {
  69. if (key.length == 1) {
  70. redisTemplate.delete(key[0]);
  71. } else {
  72. List<String> list = new ArrayList<>(Arrays.asList(key));
  73. redisTemplate.delete(list);
  74. }
  75. }
  76. }
  77. /**
  78. * 删除缓存
  79. *
  80. * @param keys 可以传一个值 或多个
  81. */
  82. @SuppressWarnings("unchecked")
  83. public void del(Collection keys) {
  84. if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(keys)) {
  85. redisTemplate.delete(keys);
  86. }
  87. }
  88. // ============================String=============================
  89. /**
  90. * 普通缓存获取
  91. *
  92. * @param key 键
  93. * @return 值
  94. */
  95. public Object get(String key) {
  96. return key == null ? null : redisTemplate.opsForValue().get(key);
  97. }
  98. /**
  99. * 普通缓存放入
  100. *
  101. * @param key 键
  102. * @param value 值
  103. * @return true成功 false失败
  104. */
  105. public boolean set(String key, Object value) {
  106. try {
  107. redisTemplate.opsForValue().set(key, value);
  108. return true;
  109. } catch (Exception e) {
  110. e.printStackTrace();
  111. return false;
  112. }
  113. }
  114. /**
  115. * 普通缓存放入并设置时间
  116. *
  117. * @param key 键
  118. * @param value 值
  119. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  120. * @return true成功 false 失败
  121. */
  122. public boolean set(String key, Object value, long time) {
  123. try {
  124. if (time > 0) {
  125. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  126. } else {
  127. set(key, value);
  128. }
  129. return true;
  130. } catch (Exception e) {
  131. e.printStackTrace();
  132. return false;
  133. }
  134. }
  135. /**
  136. * 递增
  137. *
  138. * @param key 键
  139. * @param delta 要增加几(大于0)
  140. * @return
  141. */
  142. public long incr(String key, long delta) {
  143. if (delta < 0) {
  144. throw new RuntimeException("递增因子必须大于0");
  145. }
  146. return redisTemplate.opsForValue().increment(key, delta);
  147. }
  148. /**
  149. * 递减
  150. *
  151. * @param key 键
  152. * @param delta 要减少几(小于0)
  153. * @return
  154. */
  155. public long decr(String key, long delta) {
  156. if (delta < 0) {
  157. throw new RuntimeException("递减因子必须大于0");
  158. }
  159. return redisTemplate.opsForValue().increment(key, -delta);
  160. }
  161. // ================================Hash=================================
  162. /**
  163. * HashGet
  164. *
  165. * @param key 键 不能为null
  166. * @param item 项 不能为null
  167. * @return 值
  168. */
  169. public Object hget(String key, String item) {
  170. return redisTemplate.opsForHash().get(key, item);
  171. }
  172. /**
  173. * 获取hashKey对应的所有键值
  174. *
  175. * @param key 键
  176. * @return 对应的多个键值
  177. */
  178. public Map<Object, Object> hmget(String key) {
  179. Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
  180. return entries;
  181. }
  182. /**
  183. * HashSet
  184. *
  185. * @param key 键
  186. * @param map 对应多个键值
  187. * @return true 成功 false 失败
  188. */
  189. public boolean hmset(String key, Map<String, Object> map) {
  190. try {
  191. redisTemplate.opsForHash().putAll(key, map);
  192. return true;
  193. } catch (Exception e) {
  194. e.printStackTrace();
  195. return false;
  196. }
  197. }
  198. /**
  199. * HashSet 并设置时间
  200. *
  201. * @param key 键
  202. * @param map 对应多个键值
  203. * @param time 时间(秒)
  204. * @return true成功 false失败
  205. */
  206. public boolean hmset(String key, Map<String, Object> map, long time) {
  207. try {
  208. redisTemplate.opsForHash().putAll(key, map);
  209. if (time > 0) {
  210. expire(key, time);
  211. }
  212. return true;
  213. } catch (Exception e) {
  214. e.printStackTrace();
  215. return false;
  216. }
  217. }
  218. /**
  219. * 向一张hash表中放入数据,如果存在就覆盖原来的值。
  220. *
  221. * @param key 键
  222. * @param item 项
  223. * @param value 值
  224. * @return true 成功 false失败
  225. */
  226. public boolean hset(String key, String item, Object value) {
  227. try {
  228. redisTemplate.opsForHash().put(key, item, value);
  229. return true;
  230. } catch (Exception e) {
  231. e.printStackTrace();
  232. return false;
  233. }
  234. }
  235. /**
  236. * 向一张hash表中放入数据,如果存在就覆盖原来的值。
  237. *
  238. * @param key 键
  239. * @param item 项
  240. * @param value 值
  241. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  242. * @return true 成功 false失败
  243. */
  244. public boolean hset(String key, String item, Object value, long time) {
  245. try {
  246. redisTemplate.opsForHash().put(key, item, value);
  247. if (time > 0) {
  248. expire(key, time);
  249. }
  250. return true;
  251. } catch (Exception e) {
  252. e.printStackTrace();
  253. return false;
  254. }
  255. }
  256. /**
  257. * 删除hash表中的值
  258. *
  259. * @param key 键 不能为null
  260. * @param item 项 可以使多个 不能为null
  261. * 返回被删除的数量
  262. */
  263. public Long hdel(String key, Object... item) {
  264. return redisTemplate.opsForHash().delete(key, item);
  265. }
  266. /**
  267. * 删除hash表中的值
  268. *
  269. * @param key 键 不能为null
  270. * @param items 项 可以使多个 不能为null
  271. */
  272. public void hdel(String key, Collection items) {
  273. redisTemplate.opsForHash().delete(key, items.toArray());
  274. }
  275. /**
  276. * 判断hash表中是否有该项的值
  277. *
  278. * @param key 键 不能为null
  279. * @param item 项 不能为null
  280. * @return true 存在 false不存在
  281. */
  282. public boolean hHasKey(String key, String item) {
  283. return redisTemplate.opsForHash().hasKey(key, item);
  284. }
  285. /**
  286. * hash数据类型:给元素一个增量 如果不存在,就会创建一个 并把新增后的值返回
  287. *
  288. * @param key 键
  289. * @param item 项
  290. * @param delta 要增加几(大于0)
  291. * @return
  292. */
  293. public double hincr(String key, String item, double delta) {
  294. return redisTemplate.opsForHash().increment(key, item, delta);
  295. }
  296. // ============================set=============================
  297. /**
  298. * 根据key获取Set中的所有值
  299. *
  300. * @param key 键
  301. * @return
  302. */
  303. public Set<Object> sGet(String key) {
  304. try {
  305. return redisTemplate.opsForSet().members(key);
  306. } catch (Exception e) {
  307. e.printStackTrace();
  308. return null;
  309. }
  310. }
  311. /**
  312. * 根据value从一个set中查询,是否存在
  313. *
  314. * @param key 键
  315. * @param value 值
  316. * @return true 存在 false不存在
  317. */
  318. public boolean sHasKey(String key, Object value) {
  319. try {
  320. return redisTemplate.opsForSet().isMember(key, value);
  321. } catch (Exception e) {
  322. e.printStackTrace();
  323. return false;
  324. }
  325. }
  326. /**
  327. * 将数据放入set缓存
  328. *
  329. * @param key 键
  330. * @param values 值 可以是多个
  331. * @return 成功个数
  332. */
  333. public long sSet(String key, Object... values) {
  334. try {
  335. return redisTemplate.opsForSet().add(key, values);
  336. } catch (Exception e) {
  337. e.printStackTrace();
  338. return 0;
  339. }
  340. }
  341. /**
  342. * 将数据放入set缓存
  343. *
  344. * @param key 键
  345. * @param values 值 可以是多个
  346. * @return 成功个数
  347. */
  348. public long sSet(String key, Collection values) {
  349. try {
  350. return redisTemplate.opsForSet().add(key, values.toArray());
  351. } catch (Exception e) {
  352. e.printStackTrace();
  353. return 0;
  354. }
  355. }
  356. /**
  357. * 将set数据放入缓存
  358. *
  359. * @param key 键
  360. * @param time 时间(秒)
  361. * @param values 值 可以是多个
  362. * @return 成功个数
  363. */
  364. public long sSetAndTime(String key, long time, Object... values) {
  365. try {
  366. Long count = redisTemplate.opsForSet().add(key, values);
  367. if (time > 0)
  368. expire(key, time);
  369. return count;
  370. } catch (Exception e) {
  371. e.printStackTrace();
  372. return 0;
  373. }
  374. }
  375. /**
  376. * 获取set缓存的长度
  377. *
  378. * @param key 键
  379. * @return
  380. */
  381. public long sGetSetSize(String key) {
  382. try {
  383. return redisTemplate.opsForSet().size(key);
  384. } catch (Exception e) {
  385. e.printStackTrace();
  386. return 0;
  387. }
  388. }
  389. /**
  390. * 移除值为value的
  391. *
  392. * @param key 键
  393. * @param values 值 可以是多个
  394. * @return 移除的个数
  395. */
  396. public long setRemove(String key, Object... values) {
  397. try {
  398. Long count = redisTemplate.opsForSet().remove(key, values);
  399. return count;
  400. } catch (Exception e) {
  401. e.printStackTrace();
  402. return 0;
  403. }
  404. }
  405. // ===============================list=================================
  406. /**
  407. * 获取list缓存的内容
  408. *
  409. * @param key 键
  410. * @param start 开始
  411. * @param end 结束 0 到 -1代表所有值
  412. * @return
  413. */
  414. public List<Object> lGet(String key, long start, long end) {
  415. try {
  416. return redisTemplate.opsForList().range(key, start, end);
  417. } catch (Exception e) {
  418. e.printStackTrace();
  419. return null;
  420. }
  421. }
  422. /**
  423. * 获取list缓存的长度
  424. *
  425. * @param key 键
  426. * @return
  427. */
  428. public long lGetListSize(String key) {
  429. try {
  430. return redisTemplate.opsForList().size(key);
  431. } catch (Exception e) {
  432. e.printStackTrace();
  433. return 0;
  434. }
  435. }
  436. /**
  437. * 通过索引 获取list中的值
  438. *
  439. * @param key 键
  440. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  441. * @return
  442. */
  443. public Object lGetIndex(String key, long index) {
  444. try {
  445. return redisTemplate.opsForList().index(key, index);
  446. } catch (Exception e) {
  447. e.printStackTrace();
  448. return null;
  449. }
  450. }
  451. /**
  452. * 将list放入缓存
  453. *
  454. * @param key 键
  455. * @param value 值
  456. * @return
  457. */
  458. public boolean lSet(String key, Object value) {
  459. try {
  460. redisTemplate.opsForList().rightPush(key, value);
  461. return true;
  462. } catch (Exception e) {
  463. e.printStackTrace();
  464. return false;
  465. }
  466. }
  467. /**
  468. * 将list放入缓存
  469. *
  470. * @param key 键
  471. * @param value 值
  472. * @param time 时间(秒)
  473. * @return
  474. */
  475. public boolean lSet(String key, Object value, long time) {
  476. try {
  477. redisTemplate.opsForList().rightPush(key, value);
  478. if (time > 0)
  479. expire(key, time);
  480. return true;
  481. } catch (Exception e) {
  482. e.printStackTrace();
  483. return false;
  484. }
  485. }
  486. /**
  487. * 将list放入缓存
  488. *
  489. * @param key 键
  490. * @param value 值
  491. * @return
  492. */
  493. public boolean lSet(String key, List<Object> value) {
  494. try {
  495. redisTemplate.opsForList().rightPushAll(key, value);
  496. return true;
  497. } catch (Exception e) {
  498. e.printStackTrace();
  499. return false;
  500. }
  501. }
  502. /**
  503. * 将list放入缓存
  504. *
  505. * @param key 键
  506. * @param value 值
  507. * @param time 时间(秒)
  508. * @return
  509. */
  510. public boolean lSet(String key, List<Object> value, long time) {
  511. try {
  512. redisTemplate.opsForList().rightPushAll(key, value);
  513. if (time > 0)
  514. expire(key, time);
  515. return true;
  516. } catch (Exception e) {
  517. e.printStackTrace();
  518. return false;
  519. }
  520. }
  521. /**
  522. * 根据索引修改list中的某条数据
  523. *
  524. * @param key 键
  525. * @param index 索引
  526. * @param value 值
  527. * @return
  528. */
  529. public boolean lUpdateIndex(String key, long index, Object value) {
  530. try {
  531. redisTemplate.opsForList().set(key, index, value);
  532. return true;
  533. } catch (Exception e) {
  534. e.printStackTrace();
  535. return false;
  536. }
  537. }
  538. /**
  539. * 移除N个值为value
  540. *
  541. * @param key 键
  542. * @param count 移除多少个
  543. * @param value 值
  544. * @return 移除的个数
  545. */
  546. public long lRemove(String key, long count, Object value) {
  547. try {
  548. Long remove = redisTemplate.opsForList().remove(key, count, value);
  549. return remove;
  550. } catch (Exception e) {
  551. e.printStackTrace();
  552. return 0;
  553. }
  554. }
  555. // ===============================Zset=================================
  556. /**
  557. * 给key键的value增加value分数,没有则会创建。
  558. *
  559. * @param key 键
  560. * @param value 值
  561. * @param score 分数
  562. */
  563. public Double incrementScore(String key, String value, double score) {
  564. //Boolean add = redisTemplate.boundZSetOps(key).add(value, score);
  565. Double add = redisTemplate.boundZSetOps(key).incrementScore(value, score);
  566. return add;
  567. }
  568. /**
  569. * 获得指定Zset元素的分数
  570. *
  571. * @param key
  572. * @param value
  573. * @return
  574. */
  575. public Double score(String key, String value) {
  576. Double score = redisTemplate.boundZSetOps(key).score(value);
  577. return score;
  578. }
  579. /**
  580. * 升序查询key集合内[endTop,startTop]如果是负数表示倒数
  581. * endTop=-1,startTop=0表示获取所有数据。
  582. *
  583. * @param key
  584. * @param startPage
  585. * @param endPage
  586. */
  587. public Set<ZSetOperations.TypedTuple<Object>> rangeWithScores(String key, int startPage, int endPage) {
  588. Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.boundZSetOps(key).rangeWithScores(startPage, endPage);
  589. return set;
  590. }
  591. /**
  592. * 降序查询key集合内[endTop,startTop],如果是负数表示倒数
  593. * endTop=-1,startTop=0表示获取所有数据。
  594. *
  595. * @param key
  596. * @param startPage
  597. * @param endPage
  598. */
  599. public Set<ZSetOperations.TypedTuple<Object>> reverseRangeWithScores(String key, int startPage, int endPage) {
  600. Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.boundZSetOps(key).reverseRangeWithScores(startPage, endPage);
  601. return set;
  602. }
  603. /**
  604. * 批量新增数据
  605. *
  606. * @param key
  607. * @param set
  608. * @return
  609. */
  610. public Long zsetAdd(String key, Set set) {
  611. Long add = redisTemplate.boundZSetOps(key).add(set);
  612. return add;
  613. }
  614. /**
  615. * 删除指定键的指定下标范围数据
  616. *
  617. * @param key
  618. * @param startPage
  619. * @param endPage
  620. */
  621. public Long zsetRemoveRange(String key, int startPage, int endPage) {
  622. Long l = redisTemplate.boundZSetOps(key).removeRange(startPage, endPage);
  623. return l;
  624. }
  625. /**
  626. * 删除指定键的指定值
  627. *
  628. * @param key
  629. * @param value
  630. */
  631. public Long zsetRemove(String key, String value) {
  632. Long remove = redisTemplate.boundZSetOps(key).remove(value);
  633. return remove;
  634. }
  635. }

到此这篇关于Redis实战之商城购物车功能的实现代码的文章就介绍到这了,更多相关Redis商城购物车内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号