(1).创建数据库test ,创建表shop(字段id,total),商品id是1,商品总数10
(2).PHP模拟购买,商品数量大于0才能购买
<?php //连接数据库 $con=mysqli_connect("192.168.2.186","root","root","test"); //查询商品数量是否大于0 $res=mysqli_fetch_assoc(mysqli_query($con,'SELECT total FROM shop WHERE id=1 LIMIT 1')); if($res['total']>0){ mysqli_query($con,'UPDATE shop SET total=total-1 WHERE id=1'); } unset($res); mysqli_close($con); ?>
(3).ab.exe进行高并发测试
ab -n 500 -c 500 http://test.cn/
(4).数据库结果:
高并发下这样完全不行
(5).我们可以使用where条件来处理,更新的时候加上where条件即可,更新的时候更新失败说明库存已经不足
<?php //连接数据库 $con=mysqli_connect("192.168.2.186","root","root","test"); //查询商品数量是否大于0 $res=mysqli_fetch_assoc(mysqli_query($con,'SELECT total FROM shop WHERE id=1 LIMIT 1')); if($res['total']>0){ mysqli_query($con,'UPDATE shop SET total=total-1 WHERE id=1 and total>0'); } unset($res); mysqli_close($con); ?>