1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| /** * 初始化红包到Redis * @param packetId 红包ID * @param totalPrice 总金额(单位:分) * @param totalNum 总数量 * @param amounts 预生成的红包金额列表(单位:分) */ public boolean initRedPacket(Long packetId, Integer totalPrice, Integer totalNum, List<Integer> amounts) { try { // 1. 存储红包基本信息(使用Hash) Map<String, String> packetInfo = new HashMap<>(); packetInfo.put("totalPrice", String.valueOf(totalPrice)); packetInfo.put("totalNum", String.valueOf(totalNum)); packetInfo.put("remainPrice", String.valueOf(totalPrice)); packetInfo.put("remainCount", String.valueOf(totalNum)); packetInfo.put("status", "1"); // 1-进行中 packetInfo.put("createTime", String.valueOf(System.currentTimeMillis()));
stringRedisTemplate.opsForHash().putAll(RedPacketRedisStructure.Keys.packetInfo(packetId), packetInfo);
// 设置过期时间(24小时) stringRedisTemplate.expire(RedPacketRedisStructure.Keys.packetInfo(packetId), 24, TimeUnit.HOURS);
// 2. 预生成红包金额列表(使用List,单位:分) String amountsKey = RedPacketRedisStructure.Keys.packetAmounts(packetId); for (Integer amount : amounts) { stringRedisTemplate.opsForList().rightPush(amountsKey, String.valueOf(amount)); } stringRedisTemplate.expire(amountsKey, 24, TimeUnit.HOURS);
// 3. 初始化剩余数量计数器(使用String) stringRedisTemplate.opsForValue().set(RedPacketRedisStructure.Keys.packetCount(packetId), String.valueOf(totalNum)); stringRedisTemplate.expire(RedPacketRedisStructure.Keys.packetCount(packetId), 24, TimeUnit.HOURS);
// 4. 初始化已抢用户集合(Set) String grabbedKey = RedPacketRedisStructure.Keys.packetGrabbed(packetId); // 添加一个占位符,确保集合存在 stringRedisTemplate.opsForSet().add(grabbedKey, "placeholder"); stringRedisTemplate.opsForSet().remove(grabbedKey, "placeholder"); stringRedisTemplate.expire(grabbedKey, 24, TimeUnit.HOURS);
log.info("红包初始化成功,packetId: {}, totalPrice: {}, totalNum: {}", packetId, totalPrice, totalNum); return true; } catch (Exception e) { log.error("初始化红包失败", e); return false; } }
|