search
HomeDatabaseRedisHow to use redis to create a flash sale support 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');

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;);
    }

    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

    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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

    Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

    Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

    Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

    Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

    Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

    Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

    Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

    Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

    Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

    Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

    Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

    Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

    Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

    Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

    Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

    See all articles

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools