php redis实现购物车
PHP Redis 实现购物车方案
连接 Redis
确保已安装 PHP Redis 扩展,通过 redis 类建立连接:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
数据结构设计
使用哈希表(Hash)存储用户购物车数据,键格式为 cart:user_id,字段为商品ID,值为商品数量:
$userId = 1001;
$cartKey = "cart:{$userId}";
添加商品
通过 hSet 或 hIncrBy 实现商品添加或数量增减:
$productId = 'p123';
$quantity = 2;
$redis->hIncrBy($cartKey, $productId, $quantity);
删除商品
使用 hDel 移除指定商品:

$redis->hDel($cartKey, $productId);
更新商品数量
直接覆盖原有数量值:
$newQuantity = 5;
$redis->hSet($cartKey, $productId, $newQuantity);
获取购物车内容
通过 hGetAll 获取所有商品数据:

$cartItems = $redis->hGetAll($cartKey);
foreach ($cartItems as $id => $qty) {
echo "商品ID: {$id}, 数量: {$qty}";
}
清空购物车
删除整个哈希键:
$redis->del($cartKey);
商品总数统计
使用 hLen 计算商品种类数,hVals 配合 array_sum 计算总件数:
$itemTypes = $redis->hLen($cartKey);
$totalItems = array_sum($redis->hVals($cartKey));
过期时间设置
为购物车设置自动过期(如30天):
$redis->expire($cartKey, 2592000);
注意事项
- 商品信息需另存数据库,Redis 仅存储 ID 和数量
- 高并发场景建议使用
WATCH+ 事务保证数据一致性 - 定期清理长期未活跃的购物车数据






