Home > Database > Redis > How to use Redis linked list to solve the problem of oversold products with high concurrency

How to use Redis linked list to solve the problem of oversold products with high concurrency

王林
Release: 2023-05-27 13:01:19
forward
1167 people have browsed it

Implementation Principle

Use redis linked list to do it, because the pop operation is atomic, even if many users arrive at the same time, they will be executed in sequence, which is recommended.

Implementation steps

The first step is to put the product inventory into the queue

/**
 * 添加商品数量到商品队列
 * @param int $couponId 优惠券ID
 */
function addCoupons($couponId)
{
    //1.初始化Redis连接
    $redis = new Redis();
    if (!$redis->connect('127.0.0.1', 6379)) {
        trigger_error('Redis连接出错!!!', E_USER_ERROR);
    } else {
        echo &#39;连接正常<br>&#39;;
    }

    //根据优惠券ID从数据库中查询该优惠券的库存量
    //$sql = "select id, stock from coupon where id = {$couponId}";
    $stock = 10; //假设10就是我们从数据库中查询出的该优惠券在数据库中的库存量

    //我们现在将这10个库存放入到以该商品ID为key的redis链表中,有几件库存,就存入多少次1,链表长度代表商品库存数
    for($i = 0; $i < $stock; $i++) {
        $redis->lPush("secKill:".$couponId.":stock", 1);
    }

    $redis->close();
}
$couponId = 11211;
addCoupons($couponId);
Copy after login

We call this method, and then check redis, 10 elements have been added to the linked list

How to use Redis linked list to solve the problem of oversold products with high concurrency

The second step is to start the rush purchase and set the cache cycle of the inventory.

This step is determined according to your own business. If the business stipulates, this coupon will be released 2 minutes for users to grab, then use the expire() method to set a validity period for the linked list. Even if it is not sold out within the validity period, there is still stock and users will not be allowed to grab it (because our company’s business does not grab coupons The coupon sets the validity period, so I don’t need to do this step)

//设置链表有效期是两分钟
$redis->expire(&#39;key&#39;, 120);
Copy after login

The third step, the client performs the instant snap-up operation

/**
 * 抢优惠券(秒杀)
 * @param int $couponId 商品ID
 * @param int $uid 用户ID
 * @return bool
 */
function secKill($couponId, $uid)
{
    //1.初始化Redis连接
    $redis = new Redis();
    if (!$redis->connect(&#39;127.0.0.1&#39;, 6379)) {
        trigger_error(&#39;Redis连接出错!!!&#39;, E_USER_ERROR);
    } else {
        echo &#39;连接正常<br>&#39;;
    }

    //将已经成功抢购的用户添加到该以该商品ID为key的集合(set)中
    //如果用户已经在集合中,说明用户已经成功秒杀过一次了,不允许再次参与秒杀
    if ($redis->sIsMember(&#39;secKill:&#39;.$couponId.&#39;:uid&#39;, $uid)) {
        echo &#39;秒杀失败&#39;;
        return false;
    }

    //秒杀商品的库存key
    $key = &#39;secKill:&#39;.$couponId.&#39;:stock&#39;;

    //从以该优惠券ID为key的链表中弹出一个值,如果有值,证明优惠券还有库存
    $isSockNotEmpty = $redis->lPop($key);

    //判断库存,如果库存大于0,则减库存,将该成功秒杀用户加入哈希表,如果小于等于0,秒杀结束
    if ($isSockNotEmpty != 1) {
        echo &#39;秒杀已结束&#39;;
        return false;
    }

    //抢券成功,将优惠券ID和UID放入到队列中,由一个单独的进程队列来消费队列里的数据,向用户推送抢到的优惠券
    $redis->lPush(&#39;couponOrder&#39;, $couponId.&#39;+&#39;.$uid);

    //将成功抢券的用户记录到集合中,防止被已抢过的用户再次秒杀
    $redis->sAdd(&#39;secKill:&#39;.$couponId.&#39;:uid&#39;, $uid);
    $redis->close();
    return true;
}

$couponId = 11211;
$uid      = mt_rand(1, 100);
secKill($couponId, $uid);
Copy after login

The fourth step, the successful flash sale users are entered into the database to persist the data , for purchases where the concurrency is not very large, we can directly write the information into the database after a successful purchase in the third step. For purchases where the concurrency is relatively large, it can be put into the RabbitMQ message queue for consumption (it is recommended to use the RabbitMQ queue instead of redis because RabbitMQ can guarantee that messages are 100% consumed, while redis is relatively less stable and reliable)

//此处代码省略
//根据自己的业务场景看看是入数据库还是放入rabbitMQ消息队列中消费
Copy after login

Now we use the ab tool to simulate coupon grabbing behavior under high concurrency (2000 requests, 100 concurrency)

ab -n 2000 -c 100 www.test.com/
Copy after login

Then we use Redis Desktop Manager to view the Redis results

Similarly, there are already 10 pieces of information containing user uid and coupon id in the couponOrder queue. This information can be used by the queue Consumption.

How to use Redis linked list to solve the problem of oversold products with high concurrency

#At the same time, the UID information of 10 users is also saved in the user coupon collection.

How to use Redis linked list to solve the problem of oversold products with high concurrency

The above is the detailed content of How to use Redis linked list to solve the problem of oversold products with high concurrency. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template