使用 redis 保存库存的时候,可以使用lua脚本进行原子性操作,保证库存不超。
local full_key = KEYS[1] local item_id = KEYS[2] local incr_num = tonumber(ARGV[1]) local max_num = tonumber(ARGV[2]) -- debug --redis.log(redis.LOG_NOTICE, "full_key=" .. full_key .. ",type=" .. item_id .. ",v=" .. incr_num .. ",max=" .. max_num) local current_value = redis.call("HGET", full_key, item_id) -- 数据类型检测 if current_value == false then current_value = 0 else current_value = tonumber(current_value) end -- 当前库存水位小于最大库存,则可以累积 if current_value < max_num then redis.call("HINCRBY", full_key, item_id, incr_num) -- 成功添加库存 return "ADDED" else -- 库存已满 return "FULL" end
PHP的使用方法
保证00001号商品的库存不超过100,每次加1
// 忽略 load 脚本到redis中 $sha = sha1($lua_script_content); $res = $redis->evalSha($sha, ['some_project:some_stock', '00001', 1, 100], 2) if ($res == 'ADDED') { echo '添加成功'; } else { echo '库存满'; }