视角:技术开发者
一、购物车的特殊需求
在反向海淘业务中,购物车不同于普通电商。用户可能同时从淘宝、1688多个店铺选商品,而且很多商品需要满足最低起批量。另外,用户可能几天后才提交代购集运,购物车数据需要持久化但不能无限增长。
我们在Taocarts系统中使用Redis来存储购物车数据,设计了按商家分组的购物车结构,并支持自动过期清理。分享实现代码。
二、数据结构设计
// 购物车商品项
@Data
public class CartItem {
private Long itemId; // 商品ID
private String title;
private String skuProperties; // 所选规格JSON
private Integer quantity;
private BigDecimal price;
private Long shopId; // 店铺ID
private Integer minOrderQty; // 最低起批量
}
// 购物车整体结构:Hash存储,key=cart:userId,field=shopId,value=该店铺下的商品列表JSON
三、核心操作
@Service
public class CartService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String CART_KEY_PREFIX = "cart:";
// 添加商品到购物车
public void addItem(Long userId, CartItem item) {
String key = CART_KEY_PREFIX + userId;
String shopKey = String.valueOf(item.getShopId());
// 获取该店铺现有商品列表
List<CartItem> shopItems = getShopItems(userId, item.getShopId());
Optional<CartItem> existing = shopItems.stream()
.filter(i -> i.getItemId().equals(item.getItemId())
&& i.getSkuProperties().equals(item.getSkuProperties()))
.findFirst();
if (existing.isPresent()) {
existing.get().setQuantity(existing.get().getQuantity() + item.getQuantity());
} else {
shopItems.add(item);
}
// 序列化存储
String json = JSON.toJSONString(shopItems);
redisTemplate.opsForHash().put(key, shopKey, json);
// 设置整个购物车的过期时间为7天
redisTemplate.expire(key, Duration.ofDays(7));
}
// 移除商品
public void removeItem(Long userId, Long shopId, Long itemId, String sku) {
String key = CART_KEY_PREFIX + userId;
List<CartItem> shopItems = getShopItems(userId, shopId);
shopItems.removeIf(i -> i.getItemId().equals(itemId) && i.getSkuProperties().equals(sku));
if (shopItems.isEmpty()) {
redisTemplate.opsForHash().delete(key, String.valueOf(shopId));
} else {
redisTemplate.opsForHash().put(key, String.valueOf(shopId), JSON.toJSONString(shopItems));
}
}
// 获取购物车所有商品(按店铺分组)
public Map<Long, List<CartItem>> getCart(Long userId) {
String key = CART_KEY_PREFIX + userId;
Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
Map<Long, List<CartItem>> result = new HashMap<>();
for (Map.Entry<Object, Object> entry : entries.entrySet()) {
Long shopId = Long.valueOf(entry.getKey().toString());
List<CartItem> items = JSON.parseArray(entry.getValue().toString(), CartItem.class);
result.put(shopId, items);
}
return result;
}
private List<CartItem> getShopItems(Long userId, Long shopId) {
String key = CART_KEY_PREFIX + userId;
String json = (String) redisTemplate.opsForHash().get(key, String.valueOf(shopId));
if (json == null) {
return new ArrayList<>();
}
return JSON.parseArray(json, CartItem.class);
}
}
四、最低起批量校验
用户在结算时,需要校验每个店铺的商品数量是否达到最低起批量。
public void validateMinOrderQty(Long userId) {
Map<Long, List<CartItem>> cart = getCart(userId);
for (Map.Entry<Long, List<CartItem>> entry : cart.entrySet()) {
for (CartItem item : entry.getValue()) {
if (item.getQuantity() < item.getMinOrderQty()) {
throw new BusinessException(String.format("商品【%s】最少需要购买%d件", item.getTitle(), item.getMinOrderQty()));
}
}
}
}
五、过期清理与主动通知
购物车7天自动过期。但用户可能忘记,我们在过期前1天发送提醒。
@Component
public class CartExpirationListener implements KeyExpirationEventListener {
@Override
public void onKeyExpired(String key) {
if (key.startsWith("cart:")) {
Long userId = Long.valueOf(key.substring(5));
// 发送站内信提醒
notificationService.sendCartExpireWarning(userId);
}
}
}
注意:Redis的key过期事件默认不开启,需要在redis.conf中配置notify-keyspace-events Ex。
六、与Taocarts系统的集成
上述购物车逻辑已在Taocarts系统中实现。Taocarts系统作为代购源码,购物车模块还支持“代购集运”的批量选择、运费预估等功能。做反向海淘独立站可以直接使用。