zoukankan      html  css  js  c++  java
  • php结合redis实现高并发下的抢购、秒杀功能

    抢购、秒杀是如今很常见的一个应用场景,主要需要解决的问题有两个:
    1 高并发对数据库产生的压力
    2 竞争状态下如何解决库存的正确减少("超卖"问题)
    对于第一个问题,已经很容易想到用缓存来处理抢购,避免直接操作数据库,例如使用Redis。
    重点在于第二个问题

    常规写法:

    查询出对应商品的库存,看是否大于0,然后执行生成订单等操作,但是在判断库存是否大于0处,如果在高并发下就会有问题,导致库存量出现负数

    1. <?php  
    2. $conn=mysql_connect("localhost","big","123456");    
    3. if(!$conn){    
    4.     echo "connect failed";    
    5.     exit;    
    6. }   
    7. mysql_select_db("big",$conn);   
    8. mysql_query("set names utf8");  
    9.   
    10. $price=10;  
    11. $user_id=1;  
    12. $goods_id=1;  
    13. $sku_id=11;  
    14. $number=1;  
    15.   
    16. //生成唯一订单  
    17. function build_order_no(){  
    18.     return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);  
    19. }  
    20. //记录日志  
    21. function insertLog($event,$type=0){  
    22.     global $conn;  
    23.     $sql="insert into ih_log(event,type)   
    24.     values('$event','$type')";    
    25.     mysql_query($sql,$conn);    
    26. }  
    27.   
    28. //模拟下单操作  
    29. //库存是否大于0  
    30. $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'";//解锁 此时ih_store数据中goods_id='$goods_id' and sku_id='$sku_id' 的数据被锁住(注3),其它事务必须等待此次事务 提交后才能执行  
    31. $rs=mysql_query($sql,$conn);  
    32. $row=mysql_fetch_assoc($rs);  
    33. if($row['number']>0){//高并发下会导致超卖  
    34.     $order_sn=build_order_no();  
    35.     //生成订单    
    36.     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price)   
    37.     values('$order_sn','$user_id','$goods_id','$sku_id','$price')";    
    38.     $order_rs=mysql_query($sql,$conn);   
    39.       
    40.     //库存减少  
    41.     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";  
    42.     $store_rs=mysql_query($sql,$conn);    
    43.     if(mysql_affected_rows()){    
    44.         insertLog('库存减少成功');  
    45.     }else{    
    46.         insertLog('库存减少失败');  
    47.     }   
    48. }else{  
    49.     insertLog('库存不够');  
    50. }  
    51. ?>  

    优化方案1:将库存字段number字段设为unsigned,当库存为0时,因为字段不能为负数,将会返回false

    1. //库存减少  
    2. $sql="update ih_store set number=number-{$number} where sku_id='$sku_id' and number>0";  
    3. $store_rs=mysql_query($sql,$conn);    
    4. if(mysql_affected_rows()){    
    5.     insertLog('库存减少成功');  
    6. }  

    优化方案2:使用MySQL的事务,锁住操作的行

    1. <?php  
    2. $conn=mysql_connect("localhost","big","123456");    
    3. if(!$conn){    
    4.     echo "connect failed";    
    5.     exit;    
    6. }   
    7. mysql_select_db("big",$conn);   
    8. mysql_query("set names utf8");  
    9.   
    10. $price=10;  
    11. $user_id=1;  
    12. $goods_id=1;  
    13. $sku_id=11;  
    14. $number=1;  
    15.   
    16. //生成唯一订单号  
    17. function build_order_no(){  
    18.     return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);  
    19. }  
    20. //记录日志  
    21. function insertLog($event,$type=0){  
    22.     global $conn;  
    23.     $sql="insert into ih_log(event,type)   
    24.     values('$event','$type')";    
    25.     mysql_query($sql,$conn);    
    26. }  
    27.   
    28. //模拟下单操作  
    29. //库存是否大于0  
    30. mysql_query("BEGIN");   //开始事务  
    31. $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id' FOR UPDATE";//此时这条记录被锁住,其它事务必须等待此次事务提交后才能执行  
    32. $rs=mysql_query($sql,$conn);  
    33. $row=mysql_fetch_assoc($rs);  
    34. if($row['number']>0){  
    35.     //生成订单   
    36.     $order_sn=build_order_no();   
    37.     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price)   
    38.     values('$order_sn','$user_id','$goods_id','$sku_id','$price')";    
    39.     $order_rs=mysql_query($sql,$conn);   
    40.       
    41.     //库存减少  
    42.     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";  
    43.     $store_rs=mysql_query($sql,$conn);    
    44.     if(mysql_affected_rows()){    
    45.         insertLog('库存减少成功');  
    46.         mysql_query("COMMIT");//事务提交即解锁  
    47.     }else{    
    48.         insertLog('库存减少失败');  
    49.     }  
    50. }else{  
    51.     insertLog('库存不够');  
    52.     mysql_query("ROLLBACK");  
    53. }  
    54. ?>  


    优化方案3:使用非阻塞的文件排他锁

    1. <?php  
    2. $conn=mysql_connect("localhost","root","123456");    
    3. if(!$conn){    
    4.     echo "connect failed";    
    5.     exit;    
    6. }   
    7. mysql_select_db("big-bak",$conn);   
    8. mysql_query("set names utf8");  
    9.   
    10. $price=10;  
    11. $user_id=1;  
    12. $goods_id=1;  
    13. $sku_id=11;  
    14. $number=1;  
    15.   
    16. //生成唯一订单号  
    17. function build_order_no(){  
    18.     return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);  
    19. }  
    20. //记录日志  
    21. function insertLog($event,$type=0){  
    22.     global $conn;  
    23.     $sql="insert into ih_log(event,type)   
    24.     values('$event','$type')";    
    25.     mysql_query($sql,$conn);    
    26. }  
    27.   
    28. $fp = fopen("lock.txt", "w+");  
    29. if(!flock($fp,LOCK_EX | LOCK_NB)){  
    30.     echo "系统繁忙,请稍后再试";  
    31.     return;  
    32. }  
    33. //下单  
    34. $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'";  
    35. $rs=mysql_query($sql,$conn);  
    36. $row=mysql_fetch_assoc($rs);  
    37. if($row['number']>0){//库存是否大于0  
    38.     //模拟下单操作   
    39.     $order_sn=build_order_no();   
    40.     $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price)   
    41.     values('$order_sn','$user_id','$goods_id','$sku_id','$price')";    
    42.     $order_rs=mysql_query($sql,$conn);   
    43.       
    44.     //库存减少  
    45.     $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";  
    46.     $store_rs=mysql_query($sql,$conn);    
    47.     if(mysql_affected_rows()){    
    48.         insertLog('库存减少成功');  
    49.         flock($fp,LOCK_UN);//释放锁  
    50.     }else{    
    51.         insertLog('库存减少失败');  
    52.     }   
    53. }else{  
    54.     insertLog('库存不够');  
    55. }  
    56. fclose($fp);  



    优化方案4:使用redis队列,因为pop操作是原子的,即使有很多用户同时到达,也是依次执行,推荐使用(mysql事务在高并发下性能下降很厉害,文件锁的方式也是)

    先将商品库存如队列

    1. <?php  
    2. $store=1000;  
    3. $redis=new Redis();  
    4. $result=$redis->connect('127.0.0.1',6379);  
    5. $res=$redis->llen('goods_store');  
    6. echo $res;  
    7. $count=$store-$res;  
    8. for($i=0;$i<$count;$i++){  
    9.     $redis->lpush('goods_store',1);  
    10. }  
    11. echo $redis->llen('goods_store');  
    12. ?>  


    抢购、描述逻辑

    1. <?php  
    2. $conn=mysql_connect("localhost","big","123456");    
    3. if(!$conn){    
    4.     echo "connect failed";    
    5.     exit;    
    6. }   
    7. mysql_select_db("big",$conn);   
    8. mysql_query("set names utf8");  
    9.   
    10. $price=10;  
    11. $user_id=1;  
    12. $goods_id=1;  
    13. $sku_id=11;  
    14. $number=1;  
    15.   
    16. //生成唯一订单号  
    17. function build_order_no(){  
    18.     return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);  
    19. }  
    20. //记录日志  
    21. function insertLog($event,$type=0){  
    22.     global $conn;  
    23.     $sql="insert into ih_log(event,type)   
    24.     values('$event','$type')";    
    25.     mysql_query($sql,$conn);    
    26. }  
    27.   
    28. //模拟下单操作  
    29. //下单前判断redis队列库存量  
    30. $redis=new Redis();  
    31. $result=$redis->connect('127.0.0.1',6379);  
    32. $count=$redis->lpop('goods_store');  
    33. if(!$count){  
    34.     insertLog('error:no store redis');  
    35.     return;  
    36. }  
    37.   
    38. //生成订单    
    39. $order_sn=build_order_no();  
    40. $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price)   
    41. values('$order_sn','$user_id','$goods_id','$sku_id','$price')";    
    42. $order_rs=mysql_query($sql,$conn);   
    43.   
    44. //库存减少  
    45. $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'";  
    46. $store_rs=mysql_query($sql,$conn);    
    47. if(mysql_affected_rows()){    
    48.     insertLog('库存减少成功');  
    49. }else{    
    50.     insertLog('库存减少失败');  
    51. }   


    模拟5000高并发测试
    webbench -c 5000 -t 60 http://192.168.1.198/big/index.php
    ab -r -n 6000 -c 5000  http://192.168.1.198/big/index.php


    上述只是简单模拟高并发下的抢购,真实场景要比这复杂很多,很多注意的地方
    如抢购页面做成静态的,通过ajax调用接口
    再如上面的会导致一个用户抢多个,思路:
    需要一个排队队列和抢购结果队列及库存队列。高并发情况,先将用户进入排队队列,用一个线程循环处理从排队队列取出一个用户,判断用户是否已在抢购结果队列,如果在,则已抢购,否则未抢购,库存减1,写数据库,将用户入结果队列。


    测试数据表

      1. --  
      2. -- 数据库: `big`  
      3. --  
      4.   
      5. -- --------------------------------------------------------  
      6.   
      7. --  
      8. -- 表的结构 `ih_goods`  
      9. --  
      10.   
      11.   
      12. CREATE TABLE IF NOT EXISTS `ih_goods` (  
      13.   `goods_id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
      14.   `cat_id` int(11) NOT NULL,  
      15.   `goods_name` varchar(255) NOT NULL,  
      16.   PRIMARY KEY (`goods_id`)  
      17. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;  
      18.   
      19.   
      20. --  
      21. -- 转存表中的数据 `ih_goods`  
      22. --  
      23.   
      24.   
      25. INSERT INTO `ih_goods` (`goods_id`, `cat_id`, `goods_name`) VALUES  
      26. (1, 0, '小米手机');  
      27.   
      28. -- --------------------------------------------------------  
      29.   
      30. --  
      31. -- 表的结构 `ih_log`  
      32. --  
      33.   
      34. CREATE TABLE IF NOT EXISTS `ih_log` (  
      35.   `id` int(11) NOT NULL AUTO_INCREMENT,  
      36.   `event` varchar(255) NOT NULL,  
      37.   `type` tinyint(4) NOT NULL DEFAULT '0',  
      38.   `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  
      39.   PRIMARY KEY (`id`)  
      40. ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;  
      41.   
      42. --  
      43. -- 转存表中的数据 `ih_log`  
      44. --  
      45.   
      46.   
      47. -- --------------------------------------------------------  
      48.   
      49. --  
      50. -- 表的结构 `ih_order`  
      51. --  
      52.   
      53. CREATE TABLE IF NOT EXISTS `ih_order` (  
      54.   `id` int(11) NOT NULL AUTO_INCREMENT,  
      55.   `order_sn` char(32) NOT NULL,  
      56.   `user_id` int(11) NOT NULL,  
      57.   `status` int(11) NOT NULL DEFAULT '0',  
      58.   `goods_id` int(11) NOT NULL DEFAULT '0',  
      59.   `sku_id` int(11) NOT NULL DEFAULT '0',  
      60.   `price` float NOT NULL,  
      61.   `addtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  
      62.   PRIMARY KEY (`id`)  
      63. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='订单表' AUTO_INCREMENT=1 ;  
      64.   
      65. --  
      66. -- 转存表中的数据 `ih_order`  
      67. --  
      68.   
      69.   
      70. -- --------------------------------------------------------  
      71.   
      72. --  
      73. -- 表的结构 `ih_store`  
      74. --  
      75.   
      76. CREATE TABLE IF NOT EXISTS `ih_store` (  
      77.   `id` int(11) NOT NULL AUTO_INCREMENT,  
      78.   `goods_id` int(11) NOT NULL,  
      79.   `sku_id` int(10) unsigned NOT NULL DEFAULT '0',  
      80.   `number` int(10) NOT NULL DEFAULT '0',  
      81.   `freez` int(11) NOT NULL DEFAULT '0' COMMENT '虚拟库存',  
      82.   PRIMARY KEY (`id`)  
      83. ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='库存' AUTO_INCREMENT=2 ;  
      84.   
      85. --  
      86. -- 转存表中的数据 `ih_store`  
      87. --  
      88.   
      89. INSERT INTO `ih_store` (`id`, `goods_id`, `sku_id`, `number`, `freez`) VALUES  
      90. (1, 1, 11, 500, 0); 
  • 相关阅读:
    手动配置linux(centos)的IP地址
    linux(centos)上配置nginx、mysql、phpfpm开机启动
    visual studio 2022 下载地址
    自己动手开发编译器(五)miniSharp语言的词法分析器
    自己动手开发编译器(一)编译器的模块化工程
    自己动手开发编译器(二)正则语言和正则表达式
    趣味问题:你能用Reflection.Emit生成这段代码吗?
    自己动手开发编译器(零)序言
    自己动手开发编译器特别篇——用词法分析器解决背诵圣经问题
    自己动手开发编译器(三)有穷自动机
  • 原文地址:https://www.cnblogs.com/myon/p/6668709.html
Copyright © 2011-2022 走看看