R-MS

//1.获取秒杀商品信息的接口
        public ProductInfo GetProduct(int productId)
        {
            ProductInfo productInfo = new ProductInfo();
            productInfo.PId = 1;
            productInfo.PName = "Iphone11 Pro Max";
            productInfo.PImg = @"";
            productInfo.SalePrice = 12999;
            productInfo.KillPrice = 9999;
            productInfo.KillBeginTime = DateTime.Now.AddMinutes(-30);//开始时间减30分钟
            productInfo.KillEndTime = DateTime.Now.AddMinutes(1);
            productInfo.KillCount = 150;
            //把秒杀的库存写入Redis里
            SetRedisValue("KillCount" + productInfo.PId, "150");
            return productInfo;
        }
        //2.秒杀下单
        public int KillAddOrder(OrderInfo info)
        {
            //res的返回值表示
            //1.下单成功
            //2.库存不足
            //3.三分钟内只能点一次
            int res = 0;
            //同一个用户在规定时间内只能点一次
            var UserKillTime = GetRedisValue("UserId" + info.UserId);
            if (!string.IsNullOrEmpty(UserKillTime))
            {
                //此处表示用户不是第一次下单
                DateTime dateTime = Convert.ToDateTime(UserKillTime);
                var tmpValue = DateTime.Now - dateTime;
                if (tmpValue.TotalMilliseconds < 3)
                {
                    //用户三分钟内只能点一次
                    res = 3;
                    return res;
                }
                SetRedisValue("UserId" + info.UserId, DateTime.Now.ToString());
            }
            else
            {
                //此处表示用户是第一次点击
                SetRedisValue("UserId" + info.UserId, DateTime.Now.ToString());
                //判断商品库存够不够
                var count = Convert.ToInt32(GetRedisValue("KillCount-" + info.PId));
                if (count > 0)
                {
                    count = count - 1;
                    SetRedisValue("KillCount-" + info.PId, count.ToString());
                }
                else
                {
                    res = 2;
                    return res;
                }
            }
            return res;
        }
        /// <summary>
        /// 写入redis的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private void SetRedisValue(string key, string value)
        {
            RedisClient redisClient = new RedisClient("127.0.0.1");
            redisClient.Set<string>(key, value);
        }
        /// <summary>
        /// 读取redis的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetRedisValue(string key)
        {
            RedisClient redisClient = new RedisClient("127.0.0.1");
            return redisClient.Get<string>(key);
        }
    }

posted @ 2020-06-27 08:12  G蠢蠢  阅读(115)  评论(0编辑  收藏  举报