Home

redis 秒杀 lua 脚本

    public function kill2Action()
    {
        $redis = Singleton::getRedis();
        $userId = random_int(1, 100);
        $goodsId = $this->getRequest()->getQuery('goodsId',1);
        $sha1 = $redis->script('load',$this->getLua());
        $res = $redis->evalSha($sha1,array($userId,$goodsId),2);
        echo $res?$res:'秒杀尚未开始';
    }

    public function getLua(){
        $luaScript = <<<LUA
local userId = KEYS[1]
local goodsId = KEYS[2]
local qtKey = 'SP'..goodsId..'ID'
local userKey = 'SP'..goodsId..'USER'
local goodsNumber = redis.call('get',qtKey)
if tonumber(goodsNumber) <= 0 then
return "商品库存为空"
end
local userExists = redis.call('sismember',userKey,userId)
if tonumber(userExists) == 1 then
return "当前用户已存在"
end
redis.call('decr',qtKey)
redis.call('sadd',userKey,userId)
return "秒杀成功"
LUA;
        return $luaScript;
    }

LUA脚本在Redis中的优势