.net Core基于ServiceStack Redis实现秒杀防超卖功能

首次发布:2020-01-05 22:49

完整代码链接:https://pan.baidu.com/s/1wjmBtHhVhthNNnDCFU6hKA 提取码:bg51

核心代码

class OversellTest
{//转载请保留http://www.luofenming.com/show.aspx?id=ART2020010500003
    private static bool IsGoOn = true;//秒杀活动是否结束
    public static void Show()
    {
        using (RedisStringService service = new RedisStringService())
        {
            service.Set<int>("Stock", 10);//是库存
        }

        for (int i = 0; i < 5000; i++)
        {
            int k = i;
            Task.Run(() =>//每个线程就是一个用户请求
            {
                using (RedisStringService service = new RedisStringService())
                {
                    if (IsGoOn)
                    {
                        long index = service.Decr("Stock");
                        if (index >= 0)
                        {
                            Console.WriteLine($"{k.ToString("000")}秒杀成功,秒杀商品索引为{index}");
                            //可以分队列,去数据库操作
                        }
                        else
                        {
                            if (IsGoOn)
                            {
                                IsGoOn = false;
                            }
                            Console.WriteLine($"{k.ToString("000")}秒杀失败,秒杀商品索引为{index}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"{k.ToString("000")}秒杀停止......");
                    }
                }
            });
        }

    }
}