Home  >  Article  >  Backend Development  >  How to solve the product super phenomenon when using redis flash sale?

How to solve the product super phenomenon when using redis flash sale?

WBOY
WBOYOriginal
2016-10-18 08:41:551568browse

Recently I was doing a flash sale event, and for the sake of performance and response speed, I used redis. When I was writing, I paid special attention to preventing supernormal phenomena. I used cas (check and set) optimistic locking based on redis theory. I thought that this problem should be able to eliminate it, but it still occurred. I was very confused and asked for help. The specific code is roughly as follows:

<code><?php  
header("content-type:text/html;charset=utf-8");  
$redis = new redis();  
$result = $redis->connect('10.10.10.119', 6379);  
$mywatchkey = $redis->get("mywatchkey");  
$rob_total = 100;   //抢购数量  
if($mywatchkey<$rob_total){  
    $redis->watch("mywatchkey");  
    $redis->multi();  
      
    //设置延迟,方便测试效果。  
    sleep(5);  
    //插入抢购数据  
    $redis->hSet("mywatchlist","user_id_".mt_rand(1, 9999),time());  
    $redis->set("mywatchkey",$mywatchkey+1);  
    $rob_result = $redis->exec();  
    if($rob_result){  
        $mywatchlist = $redis->hGetAll("mywatchlist");  
        echo "抢购成功!<br/>";  
        echo "剩余数量:".($rob_total-$mywatchkey-1)."<br/>";  
        echo "用户列表:<pre class="brush:php;toolbar:false">";  
        var_dump($mywatchlist);  
    }else{  
        echo "手气不好,再抢购!";exit;  
    }  
}  
?>  
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Mixed php and htmlNext article:Mixed php and html