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

 3040

这篇文章主要介绍了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

添加如下代码:

extension=php_igbinary.dll
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实现商品秒杀代码实例讲解

三、代码

<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\cache\driver\Redis;
class Miaosha extends Controller
{
    private $redis = null;
    private $cachekey = null; //缓存变量名
    private $basket = []; //私有数组,存放商品信息
    private $store = 50;
    /**
     * 购物车初始化,传入用户id
     */
    public function __construct()
    {
        parent::__construct();
        $this->redis = new \Redis(); // 实例化
        $this->redis->connect('127.0.0.1','6379');
        $this->redis->auth('zxf123456');
    }
    /**
     * 秒杀初始化
     */
    public function Ms_init()
    {
        // 删除缓存列表
        $this->redis->del($this->cachekey);
        $len = $this->redis->llen($this->cachekey);
        $count = $this->store - $len;
        for ($i=0; $i < $count; $i++) { 
            // 向库存列表推进50个,模拟50个商品库存
            $this->redis->lpush($this->cachekey,1);
        }
        echo "库存初始化完成:".$this->redis->llen($this->cachekey);
    }
 
    /**
     * 秒杀入口
     */
    public function index()
    {
        $id = 1; //商品编号
 
        if (empty($id)) {
            // 记录失败日志
            return $this->writeLog(0,'商品编号不存在'); 
        }
        // 计算库存列表长度
        $count = $this->redis->llen($this->cachekey);
        // 先判断库存是否为0,为0秒杀失败,不为0,则进行先移除一个元素,再进行数据库操作
        if ($count == 0) { //库存为0
            $this->writeLog(0,'库存为0');
            echo "库存为0";
            exit;
        } else {
            // 有库存
            //先移除一个列表元素
            $this->redis->lpop($this->cachekey);
            $ordersn = $this->build_order_no(); //生成订单
            $uid = rand(0,9999); //随机生成用户id
            $status = 1;
            // 再进行数据库操作
            $data = Db::table('ab_goods')->field('count,amount')->where('id',$id)->find(); //查找商品
            if (!$data) {
                return $this->writeLog(0,'该商品不存在');
            }
            $insert_data = [
                'order_sn' => $ordersn,
                'user_id' => $uid,
                'goods_id' => $id,
                'price' => $data['amount'],
                'status' => $status,
                'addtime' => date('Y-m-d H:i:s')
            ];
            // 订单入库
            $result = Db::table('ab_order')->insert($insert_data);
            // 自动减少一个库存
            $res = Db::table('ab_goods')->where('id',$id)->setDec('count');
            if ($res) {
                echo "第".$count."件秒杀成功";
                $this->writeLog(1,'秒杀成功');
            }else{
                echo "第".$count."件秒杀失败";
                $this->writeLog(0,'秒杀失败');
            }
        }
    }
    /**
     * 生成订单号
     */
    public function build_order_no()
    {
        return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    /**
     * 生成日志 1成功 0失败
     */
    public function writeLog($status = 1,$msg)
    {
        $data['count'] = 1;
        $data['status'] = $status;
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['msg'] = $msg;
        return Db::table('ab_log')->insertGetId($data);
    }
}

四、压力测试

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

AB测试相关参数说明

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

-t 等待响应的最大时间

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

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

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

2、测试   命令行:

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的例子;

public function sqlMs()
{
    $id = 1; //商品编号
    $count = 50;
    $ordersn = $this->build_order_no(); //生成订单
    $uid = rand(0,9999); //随机生成用户id
    $status = 1;
    // 再进行数据库操作
    $data = Db::table('ab_goods')->field('count,amount')->where('id',$id)->find(); //查找商品
    // 查询还剩多少库存
    $rs = Db::table('ab_goods')->where('id',$id)->value('count');
    if ($rs <= 0) { 
        $this->writeLog(0,'库存为0');
    }else{
        $insert_data = [
            'order_sn' => $ordersn,
            'user_id' => $uid,
            'goods_id' => $id,
            'price' => $data['amount'],
            'status' => $status,
            'addtime' => date('Y-m-d H:i:s')
        ];
        // 订单入库
        $result = Db::table('ab_order')->insert($insert_data);
        // 自动减少一个库存
        $res = Db::table('ab_goods')->where('id',$id)->setDec('count');
        if ($res) {
            echo "第".$data['count']."件秒杀成功";
            $this->writeLog(1,'秒杀成功');
        }else{
            echo "第".$data['count']."件秒杀失败";
            $this->writeLog(0,'秒杀失败');
        }
    }
}


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

评论(0)条

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

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

    编辑推荐