PHP+Redis简单的秒杀业务

ByWhat'sUs

PHP+Redis简单的秒杀业务

高并发下如何保证不超卖?因严重依赖redis,为实现高可用故redis为集群模式,直接看代码

<?php
$redisConfig = ['127.0.0.1:6379', '127.0.0.1:6380', '127.0.0.1:6381'];
$redis = new \RedisCluster(null,$redisConfig);
// 加锁,分布式锁,设置库存为1000
$redis->setnx('stock',1000);
// 模拟用户ID
$userId = rand(10000,1000000);
// lua脚本,非常简单
$lua = <<<SCRIPT
            local userId   = KEYS[1];
            local goodKey  = KEYS[2];
            local stock    = KEYS[3];
            local userExit = redis.call("sismember",goodKey,userId);
            if tonumber(userExit) == 1 then
                return 2;
            end 
            local num = redis.call("get",stock);
            if tonumber(num) <= 0 then
                return 2;
            else
                redis.call("decr",stock);
                redis.call("sadd",goodKey,userId);
            end 
            return 1;
SCRIPT;
// eval执行lua脚本
$result = $redis->eval($lua,[$userId,'goods_id','stock'],3);
if ($result == 1) {
    // 秒杀成功
    // 后续业务
} else {
    // 秒杀失败
}

About the author

What'sUs administrator

Leave a Reply

PHP Code Snippets Powered By : XYZScripts.com