Home > Article > Backend Development > How to implement flash sale function in PHP mall
How to implement the flash sale function of php mall: 1. Open the php file and connect to the redis database; 2. Create a list of products to be snapped up; 3. Simulate user requests and set up to randomly obtain 10 users to indicate successful snapping up; 4. Determine whether the user already exists in the snap-up list and obtain all the data in the list; 5. Save the snap-up users in redis to the database.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php redis implements the flash sale function, which can Relieve the pressure of instantaneous concurrency on mysql
## Scenario: At a certain point in time, the goods_id of the product =2 products for rush purchase, the product inventory is 10
//1、连接redis数据库 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis_name = 'goods_id_2';//比如商品id=2的商品参与秒杀 //2、模拟抢购,库存为10,将库存放到redis中 $num = 10; for($i=0;$i<$num;$i++){ $redis->lPush($redis_name,1);//这里用某个商品的ID作为标识 } echo "执行成功";
//1、连接redis数据库 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis_name = 'goods_id_2';//比如商品id=2的商品参与秒杀 //3、模拟用户请求,随机获取10名用户表示抢购成功 for($i=0;$i<100;$i++){ $user_id = rand(100,999); $len = $redis->lLen($redis_name); $str = ""; if(!$len || $len<=0){ $str .= $user_id."抢购已结束"; break; }else{ $redis_user_name = "goods_id_2_user_id"; //判断抢购列表中是否已存在该用户,获取列表中所有的数据 $skill_list = $redis->lrange($redis_user_name, 0, -1); if(in_array($user_id, $skill_list)){ $str .= $user_id."请勿重复提交"; }else{ $redis->rPop($redis_name); $redis->lPush($redis_user_name,$user_id."_".ceil(microtime(true)*1000)); $str .= $user_id."已抢到"; } } file_put_contents("D:/wwwroot/test/skill/cron.txt", $str."\r\n",FILE_APPEND); } echo '执行完成';
<?php $mysql_server_name = 'localhost'; //改成自己的mysql数据库服务器 $mysql_username = 'root'; //改成自己的mysql数据库用户名 $mysql_password = '123456'; //改成自己的mysql数据库密码 $mysql_database = 'test'; //改成自己的mysql数据库名 $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库 //连接数据库错误提示 if (mysqli_connect_errno($conn)) { die("连接 MySQL 失败: " . mysqli_connect_error()); } mysqli_query($conn,"set names utf8"); //数据库编码格式 //1、连接redis数据库 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis_name = 'goods_id_2';//比如商品id=2的商品参与秒杀 //2、将list队列中的数据读取出来然后执行入库 $redis_user_name = "goods_id_2_user_id"; while(true){ //判断抢购列表中是否已存在该用户,获取列表中所有的数据 $result = $redis->rpop($redis_user_name); if($result){ $skill_arr = array_filter(explode("_", $result)); $sql = "insert into skill (user_id,timestamp) values({$skill_arr[0]},{$skill_arr[1]})"; mysqli_query($conn,$sql); } } echo "执行成功";
"
The above is the detailed content of How to implement flash sale function in PHP mall. For more information, please follow other related articles on the PHP Chinese website!