How 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:
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
- 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.
- ##If the inventory deduction is successful (remainder >= 0), the rush purchase is successful and the order processing queue (list) is entered.
//随机生成会员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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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.

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.

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.

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.

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).

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.
