Files
FlashSaleSystem/src/main/resources/lua/cart_operation.lua

51 lines
1.4 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- 购物车操作Lua脚本
-- 功能:原子性地更新购物车并检查库存
-- 参数KEYS[1] = 购物车key, KEYS[2] = 库存key, ARGV[1] = 商品ID, ARGV[2] = 数量, ARGV[3] = 操作类型(add/update/remove)
-- 返回值:成功返回新数量,失败返回负数
local cart_key = KEYS[1]
local stock_key = KEYS[2]
local product_id = ARGV[1]
local quantity = tonumber(ARGV[2])
local operation = ARGV[3]
-- 获取当前库存
local current_stock = redis.call('GET', stock_key)
if current_stock == false then
return -1 -- 商品不存在
end
current_stock = tonumber(current_stock)
-- 获取购物车中当前商品数量
local cart_quantity = redis.call('HGET', cart_key, product_id)
cart_quantity = cart_quantity and tonumber(cart_quantity) or 0
local new_quantity = 0
if operation == 'add' then
new_quantity = cart_quantity + quantity
elseif operation == 'update' then
new_quantity = quantity
elseif operation == 'remove' then
redis.call('HDEL', cart_key, product_id)
return 0
else
return -2 -- 无效操作
end
-- 检查库存是否足够
if new_quantity > current_stock then
return -3 -- 库存不足
end
-- 更新购物车
if new_quantity > 0 then
redis.call('HSET', cart_key, product_id, new_quantity)
-- 设置购物车过期时间7天
redis.call('EXPIRE', cart_key, 7 * 24 * 3600)
else
redis.call('HDEL', cart_key, product_id)
end
return new_quantity