How to design high concurrency when the second kill, is to interview the e-Commerce technical position must test the topic. Share here today a Redis or memcached-based technology solution that solves repetitive commits, hyper-postbacks, and high concurrency issues.
<?php
Pre-defined Total inventory
Define ("Total_stock", 5);
Pre-defined item number
Define ("item_id", "item_001");
$userId = $_get[' userId '];
$userIdKey = item_id. ‘_‘ . $userId;
$redis = new Redis ();
If you have multiple Redis servers, you can get the address of one of the redis based on the hash of the product number
$result = $redis->connect (' master104 ', 6379);
Get the quantity that was previously picked up
$requested = $redis->get ("requested");
echo "stock before pick up:". (string) (total_stock-$requested). "<br/>";
If the collection is larger than the pre-defined inventory, the inventory is considered to be zero and is not allowed to continue
if ($requested && ($requested >= total_stock))
{
echo "has been finished, please come again next time";
Die ();
}
Check that the user has been picked up by setting a status of the user's claim to the item
If you use memcached, you can use CAS ()
if (! $redis->setnx ($userIdKey, 1))
{
echo "You have already received the product and do not allow duplicate collection";
Die ();
}
Increase the number of pick-up to reduce inventory.
Multiple incr () may be successful in high concurrency situations. But it does not matter, after the collection of more than the number of inventory, through the following if judgment, subsequent requests are invalid.
$requested = $redis->INCR ("requested");
If you try to increase it, you find that the inventory is zero and you need to reset the user pickup status
if ($requested && ($requested > Total_stock)
{
$redis->del ($userIdKey);
echo "has been finished, please come again next time";
Die ();
}
Here are some other things you can do, such as asynchronous parallel operations, sending messages to queues, and so on.
Step1
//...
Stepn
If the step is here, regardless of how the above asynchronous operation is going, we must assume that the user has already received the success.
Even if there is any failure, we need to use technical means to help users complete the above STEP1 to STEPN
echo "Successfully received!" <br/> ";
echo "stock after pick up:". (string) (total_stock-$requested). "<br/>";
?>
Design of high concurrent second kill based on redis/memcached