Table of Contents
Initialization
Instakill
Home Database Redis How to use redis to create a flash sale support demo

How to use redis to create a flash sale support demo

May 27, 2023 am 08:22 AM
redis demo

Use redis to deduct inventory for flash sales, limiting each account to only one snap-up. This simple demo uses three basic types: string, hash, and list.

  • Use string Type int value to store the remaining inventory, and reduce it by 1 after the snap-up is successful

  • Use hash to store the id of the "sold-in" member (you can ensure that the user id is the only one in the field property). Note: The uid corresponding to the field of this hash may not necessarily be a successful purchase.

  • Use list to save the list of member IDs that are actually successful in the purchase, as a queue for subsequent order processing

When I first wrote it, I tried to use string bitmap to save whether the member has successfully purchased, but this will cause problems when concurrency is high, so I later changed it to unique Field hash

2 files:

  • init.php: initialized inventory, statistical data, list of successful members, etc.

  • buy.php: rush purchase

Initialization

ini.php:

$m_redis = new YourRedisClass(); //redis类很多, 可以自己写, 也可以用predis等
$m_redis->set('rush_stock', 20);//int, 可抢购的商品总数
$m_redis->set('rush_success', 0); //int, 成功的数量
$m_redis->set('rush_fail', 0); //int, 失败的数量
$m_redis->expire('rush_queue_h', 0); //hash, 已加入抢购队列的会员的hash记录表(field是唯一的, 可限制每个uid只有一次), 不一定抢购成功
$m_redis->set('rush_got_uid', ''); //string, 抢购成功的会员uid记录, 只是为了能简单的显示抢到的会员.
$m_redis->del('rush_got_uid_l'); //list, 抢购成功的会员uid(方便抢购后的订单批次处理)
echo 'success, '.date('Y-m-d H:i:s');
Copy after login

Execute this file and initialize the quantity.

Execute "mget rush_stock rush_fail rush_success rush_got_uid" under redis-cli to confirm the initialization data

Instakill

Judgment logic:


    1. Whether the inventory is 0, if the inventory is >0, it will enter the rush buying queue


    1. ##The rush buying queue data (hash) is written successfully, and the inventory is ready to be deducted


    1. ##If the inventory deduction is successful (remainder >= 0), the rush purchase is successful and the order processing queue (list) is entered.
    2. Currently, string int is used to store inventory, and list items can also be used. Number to count, but initialization is not as simple as string type.


    buy.php
//随机生成会员id
$uid = rand(1,200);

$m_redis = new YourRedisClass(); //redis类很多, 可以自己写, 也可以用predis等

$key = 'rush_stock';
$q = $m_redis->get($key);

//1. 先判断库存数量
//库存为0, 直接无法进入抢购队列
if($q < 1){
    $m_redis->incr(&#39;rush_fail&#39;);//记录失败的数量
    die($uid.&#39;:OutOfStock&#39;);
}

//2. 判断该会员是否购买过 => 是否进入过队列
$queued = $m_redis->hSet(&#39;rush_queue_h&#39;, $uid, $uid);//这里只能判断是否进入了抢购的队列. 如果库存为0则无法进入. 进入了队列后才能抢购
if(!$queued){
    $m_redis->incr(&#39;rush_fail&#39;);//记录失败的数量
    die($uid.&#39;:queue failed&#39;);
}

//让cpu飞一会
$n = rand(20000,100000);
for($i=0; $i < $n; $i++){
    $a = rand(1,20000);
    $a = rand(1,30000);
    $a = rand(1,40000);
    $a = rand(1,50000);
    $a = rand(1,60000);
    $a = rand(1,70000);
    $a = rand(1,80000);
    $a = rand(1,90000);
}


//3. 扣减数量
$q = $m_redis->decr($key, 1);//扣减数量后会返回结果值
echo $q.&#39; left:&#39;;


////region 如果不判断操作后返回的结果,则可能会造成超发
//$m_redis->incr(&#39;q_success&#39;);//记录成功的数量  ==>这个是有bug的, 不可取
//die(&#39;:success&#39;);
////endregion

if($q < 0){
    $m_redis->incr(&#39;rush_fail&#39;);//记录失败的数量
    die($uid.&#39;:decrease fail&#39;);
}else{
    //记录成功的数量
    $m_redis->incr(&#39;rush_success&#39;);
    //记录该会员已购买
    $m_redis->append(&#39;rush_got_uid&#39;, $uid.&#39;,&#39;); //字符串追加
    $m_redis->rPush(&#39;rush_got_uid_l&#39;, $uid); //list
    die($uid.&#39;:success&#39;);
}
Copy after login

The hash in the above code saves the member uid, The member uid that just enters the rush purchase queue may not necessarily be successful in the rush purchase. Those who have not entered the rush purchase queue at all will not be in this hash and will be rejected directly because the inventory is 0.

AB stress test: Make a simple 500 concurrent requests and try a total of 2,000 requests (during testing, Nginx hangs up after 600 concurrent requests under win10)

Apache路径bin>ab -n 2000 -c 500 http://xxx.com/buy.php
Copy after login

Execute "mget rush_stock rush_fail rush_success rush_got_uid" under redis-cli to confirm the result, Check the number of possible over-issuances through the value of rush_stock

Execute "hvals rush_queue_h" to check the user IDs entering the rush purchase queue. This number >= the number of users who have successfully rushed to buy.

For the list queue For data operations, you can use the

BLPOP

command, which can implement the FIFO data processing sequence.

The above is the detailed content of How to use redis to create a flash sale support demo. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to view the version number of redis How to view the version number of redis Apr 10, 2025 pm 05:57 PM

To view the Redis version number, you can use the following three methods: (1) enter the INFO command, (2) start the server with the --version option, and (3) view the configuration file.

What to do if redis-server can't be found What to do if redis-server can't be found Apr 10, 2025 pm 06:54 PM

Steps to solve the problem that redis-server cannot find: Check the installation to make sure Redis is installed correctly; set the environment variables REDIS_HOST and REDIS_PORT; start the Redis server redis-server; check whether the server is running redis-cli ping.

How to use redis zset How to use redis zset Apr 10, 2025 pm 07:27 PM

Redis Ordered Sets (ZSets) are used to store ordered elements and sort by associated scores. The steps to use ZSet include: 1. Create a ZSet; 2. Add a member; 3. Get a member score; 4. Get a ranking; 5. Get a member in the ranking range; 6. Delete a member; 7. Get the number of elements; 8. Get the number of members in the score range.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

See all articles