阅读 213

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

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

环境:wamp,redis

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

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

一、安装Redis扩展

1.查看PHP版本信息

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

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

4.修改php.ini

添加如下代码:

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

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

5.重启Apache

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

二、数据结构

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

商品表

订单表

日志表 记录秒杀信息

三、代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?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  

  3.检测数据库数据

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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,'秒杀失败');
 }
 }
 }<br type="_moz">

到此这篇关于Thinkphp5+Redis实现商品秒杀的文章就介绍到这了,更多相关Thinkphp5+Redis实现商品秒杀内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!



文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐