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:
Whether the inventory is 0, if the inventory is >0, it will enter the rush buying queue
- ##The rush buying queue data (hash) is written successfully, and the inventory is ready to be deducted
- ##If the inventory deduction is successful (remainder >= 0), the rush purchase is successful and the order processing queue (list) is entered.
- 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.
//随机生成会员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('rush_fail');//记录失败的数量 die($uid.':OutOfStock'); } //2. 判断该会员是否购买过 => 是否进入过队列 $queued = $m_redis->hSet('rush_queue_h', $uid, $uid);//这里只能判断是否进入了抢购的队列. 如果库存为0则无法进入. 进入了队列后才能抢购 if(!$queued){ $m_redis->incr('rush_fail');//记录失败的数量 die($uid.':queue failed'); } //让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.' left:'; ////region 如果不判断操作后返回的结果,则可能会造成超发 //$m_redis->incr('q_success');//记录成功的数量 ==>这个是有bug的, 不可取 //die(':success'); ////endregion if($q < 0){ $m_redis->incr('rush_fail');//记录失败的数量 die($uid.':decrease fail'); }else{ //记录成功的数量 $m_redis->incr('rush_success'); //记录该会员已购买 $m_redis->append('rush_got_uid', $uid.','); //字符串追加 $m_redis->rPush('rush_got_uid_l', $uid); //list die($uid.':success'); }
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!

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor