Thinkphp5+Redis实现商品秒杀代码实例讲解

 4435

这篇文章主要介绍了Thinkphp5+Redis实现商品秒杀代码实例讲解,代码和步骤讲解的很清楚,有需要的同学可以借鉴参考下:


环境:wamp,redis

要求:安装WAMP,Redis,以及为PHP安装Redis扩展

秒杀功能大致思路:获取缓存列表的长度,如果长度(llen)等于0,就停止秒杀,即秒杀失败,如果长度大于0,则继续运行,先从缓存中移除一个元素(lpop),再进行数据库操作(添加订单表,商品库存数量减一),如果再进一个人秒杀,就再走一遍流程,循环往复。

一、安装Redis扩展

1、查看PHP版本信息

打开phpinfo.php,查看PHP版本,我的是PHP7.3.4,还有一个需要注意Architecture x64


Thinkphp5+Redis实现商品秒杀代码实例讲解


2、下载扩展文件

https://pecl.php.net/package/redis

https://pecl.php.net/package/igbinary

根据自己环境,选择合适的版本

3、解压

解压下载的压缩包,并把php_redis.dll、php_redis.pdb和php_igbinary.dll、php_igbinary.pdb四个文件,移至自己PHP版本对应目录下的ext文件夹下E:\phpstudy_pro\Extensions\php\php7.3.4nts\ext


Thinkphp5+Redis实现商品秒杀代码实例讲解

Thinkphp5+Redis实现商品秒杀代码实例讲解


4、修改php.ini

添加如下代码:

  1. extension=php_igbinary.dll
  2. extension=php_redis.dll

如果有这两句可以把前面的分号删掉,没有就自己添加上,要注意顺序,php_igbinary.dll 要在php_redis.dll 前面


Thinkphp5+Redis实现商品秒杀代码实例讲解


5、重启Apache

重启后,再运行phpinfo.php,查看是否安装成功


Thinkphp5+Redis实现商品秒杀代码实例讲解

二、数据结构

一共三张表,ab_goods商品表,ab_order订单表,ab_log日志表


商品表


Thinkphp5+Redis实现商品秒杀代码实例讲解

订单表


Thinkphp5+Redis实现商品秒杀代码实例讲解

日志表 记录秒杀信息


Thinkphp5+Redis实现商品秒杀代码实例讲解

三、代码

  1. <?php
  2. namespace app\index\controller;
  3. use think\Controller;
  4. use think\Db;
  5. use think\cache\driver\Redis;
  6. class Miaosha extends Controller
  7. {
  8.     private $redis = null;
  9.     private $cachekey = null; //缓存变量名
  10.     private $basket = []; //私有数组,存放商品信息
  11.     private $store = 50;
  12.     /**
  13.      * 购物车初始化,传入用户id
  14.      */
  15.     public function __construct()
  16.     {
  17.         parent::__construct();
  18.         $this->redis = new \Redis(); // 实例化
  19.         $this->redis->connect('127.0.0.1','6379');
  20.         $this->redis->auth('zxf123456');
  21.     }
  22.     /**
  23.      * 秒杀初始化
  24.      */
  25.     public function Ms_init()
  26.     {
  27.         // 删除缓存列表
  28.         $this->redis->del($this->cachekey);
  29.         $len = $this->redis->llen($this->cachekey);
  30.         $count = $this->store - $len;
  31.         for ($i=0; $i < $count; $i++) { 
  32.             // 向库存列表推进50个,模拟50个商品库存
  33.             $this->redis->lpush($this->cachekey,1);
  34.         }
  35.         echo "库存初始化完成:".$this->redis->llen($this->cachekey);
  36.     }
  37.  
  38.     /**
  39.      * 秒杀入口
  40.      */
  41.     public function index()
  42.     {
  43.         $id = 1; //商品编号
  44.  
  45.         if (empty($id)) {
  46.             // 记录失败日志
  47.             return $this->writeLog(0,'商品编号不存在'); 
  48.         }
  49.         // 计算库存列表长度
  50.         $count = $this->redis->llen($this->cachekey);
  51.         // 先判断库存是否为0,为0秒杀失败,不为0,则进行先移除一个元素,再进行数据库操作
  52.         if ($count == 0) { //库存为0
  53.             $this->writeLog(0,'库存为0');
  54.             echo "库存为0";
  55.             exit;
  56.         } else {
  57.             // 有库存
  58.             //先移除一个列表元素
  59.             $this->redis->lpop($this->cachekey);
  60.             $ordersn = $this->build_order_no(); //生成订单
  61.             $uid = rand(0,9999); //随机生成用户id
  62.             $status = 1;
  63.             // 再进行数据库操作
  64.             $data = Db::table('ab_goods')->field('count,amount')->where('id',$id)->find(); //查找商品
  65.             if (!$data) {
  66.                 return $this->writeLog(0,'该商品不存在');
  67.             }
  68.             $insert_data = [
  69.                 'order_sn' => $ordersn,
  70.                 'user_id' => $uid,
  71.                 'goods_id' => $id,
  72.                 'price' => $data['amount'],
  73.                 'status' => $status,
  74.                 'addtime' => date('Y-m-d H:i:s')
  75.             ];
  76.             // 订单入库
  77.             $result = Db::table('ab_order')->insert($insert_data);
  78.             // 自动减少一个库存
  79.             $res = Db::table('ab_goods')->where('id',$id)->setDec('count');
  80.             if ($res) {
  81.                 echo "第".$count."件秒杀成功";
  82.                 $this->writeLog(1,'秒杀成功');
  83.             }else{
  84.                 echo "第".$count."件秒杀失败";
  85.                 $this->writeLog(0,'秒杀失败');
  86.             }
  87.         }
  88.     }
  89.     /**
  90.      * 生成订单号
  91.      */
  92.     public function build_order_no()
  93.     {
  94.         return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  95.     }
  96.     /**
  97.      * 生成日志 1成功 0失败
  98.      */
  99.     public function writeLog($status = 1,$msg)
  100.     {
  101.         $data['count'] = 1;
  102.         $data['status'] = $status;
  103.         $data['addtime'] = date('Y-m-d H:i:s');
  104.         $data['msg'] = $msg;
  105.         return Db::table('ab_log')->insertGetId($data);
  106.     }
  107. }

四、压力测试

使用apache压力测试工具 AB 测试,模拟多用户秒杀商品,模拟60秒内发起3000个请求,并发600次,秒杀50个库存商品

AB测试相关参数说明

-r 指定接收到错误信息时不退出程序

-t 等待响应的最大时间

-n 指定压力测试总共的执行次数

-c 用于指定压力测试的并发数

1、初始化50个库存,运行ms_init方法

2、测试   命令行:

  1. E:\phpstudy_pro\Extensions\Apache2.4.39\bin>ab -r -t 60 -n 3000 -c 1000 http://gouwuche.zxf/index/miaosha/index


Thinkphp5+Redis实现商品秒杀代码实例讲解


3、检测数据库数据


Thinkphp5+Redis实现商品秒杀代码实例讲解

Thinkphp5+Redis实现商品秒杀代码实例讲解


日志表状态为1(秒杀成功)的数据有50人,订单表里的订单数也是50条,商品表里的商品数量变成了0(测试之前是50),商品秒杀成功完成!

如果不用redis而是直接用mysql的话,商品表订单的数量count会变成负数,而秒杀成功的人数也多余50人,订单表里的订单数量也多余50条(新测),下面是直接用Mysql的例子;

  1. public function sqlMs()
  2. {
  3.     $id = 1; //商品编号
  4.     $count = 50;
  5.     $ordersn = $this->build_order_no(); //生成订单
  6.     $uid = rand(0,9999); //随机生成用户id
  7.     $status = 1;
  8.     // 再进行数据库操作
  9.     $data = Db::table('ab_goods')->field('count,amount')->where('id',$id)->find(); //查找商品
  10.     // 查询还剩多少库存
  11.     $rs = Db::table('ab_goods')->where('id',$id)->value('count');
  12.     if ($rs <= 0) { 
  13.         $this->writeLog(0,'库存为0');
  14.     }else{
  15.         $insert_data = [
  16.             'order_sn' => $ordersn,
  17.             'user_id' => $uid,
  18.             'goods_id' => $id,
  19.             'price' => $data['amount'],
  20.             'status' => $status,
  21.             'addtime' => date('Y-m-d H:i:s')
  22.         ];
  23.         // 订单入库
  24.         $result = Db::table('ab_order')->insert($insert_data);
  25.         // 自动减少一个库存
  26.         $res = Db::table('ab_goods')->where('id',$id)->setDec('count');
  27.         if ($res) {
  28.             echo "第".$data['count']."件秒杀成功";
  29.             $this->writeLog(1,'秒杀成功');
  30.         }else{
  31.             echo "第".$data['count']."件秒杀失败";
  32.             $this->writeLog(0,'秒杀失败');
  33.         }
  34.     }
  35. }


本文网址:https://www.zztuku.com/detail-8715.html
站长图库 - Thinkphp5+Redis实现商品秒杀代码实例讲解
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐