redis 结合Lua脚本实现 秒杀、防止超卖

需求:
同1商品单个用户限购1件,库存不会超卖

1 Lua脚本,因可实现原子性操作,这个文件放到resources目录下

local userId = KEYS[1] -- 当前秒杀的用户 ID
local goodsId = KEYS[2] -- 秒杀的商品 ID
-- 订单id
local orderId = ARGV[1]

redis.log(redis.LOG_NOTICE,"秒杀商品ID:‘"..goodsId.."’,当前秒杀用户 ID:‘"..userId.."’") -- 日志记录

-- 使用一个统一的前缀来存储所有商品的库存信息
local stockHashKey = "Seckill:Stock" -- 秒杀商品的库存哈希KEY

-- 如果一个用户已经参加过秒杀了,那么不应该重复参加
-- 所有的秒杀的商品一定要保存在 SET 集合(用户 ID 不能重复)
local resultKey = "Seckill:Result:"..goodsId
local resultExists = redis.call('SISMEMBER', resultKey, userId)
redis.log(redis.LOG_NOTICE,"【"..userId.."-"..goodsId.."】当前用户参加秒杀的状态:"..resultExists)

if tonumber(resultExists) == 1 then
    return -1 -- 用户参加过秒杀了
else
    -- 获取当前商品库存数量,使用HGET命令从哈希表中获取
    local goodsCount = redis.call('HGET', stockHashKey, goodsId)
    if goodsCount == false then
        goodsCount = 0 -- 如果没有这个字段,默认库

你可能感兴趣的:(#,redis,redis,lua)