[asp.net core 1.1 供参考]SeckillPro.zip

时间:2023-06-23 09:28:35
【文件属性】:

文件名称:[asp.net core 1.1 供参考]SeckillPro.zip

文件大小:16.12MB

文件格式:ZIP

更新时间:2023-06-23 09:28:35

mvc webapi asp.net core

描述:秒杀活动,模拟,架构:mvc+webapi+console+redis,netcore开发 static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.GetEncoding("GB2312"); try { Console.WriteLine("是否开启处理抢购队列(Y):"); Console.ReadLine(); Console.WriteLine($"开启抢购任务监控中..."); var shopsKey = EnumHelper.EmDataKey.ShoppingHash.ToString(); while (true) { //匹配出QiangOrderEqueue_xxx格式的抢单队列keys var matchKey = $"{EnumHelper.EmDataKey.QiangOrderEqueue.ToString()}_*"; var matches = _redis.MatchKeys(matchKey).Result; var matchLen = matches.Count; if (matchLen <= 0) { continue; } //根据key获取对应的商品,并加载对应的商品抢单任务处理 foreach (var item in matches) { var itemArr = item.Split('_'); if (itemArr.Length <= 1) { continue; } var shopId = itemArr[1]; var shop = _redis.GetHashField(shopsKey, shopId).Result; if (shop == null || _dicTask.ContainsKey(shop.Id)) { continue; } //加入排重任务dic _dicTask.Add(shop.Id, shop.Id); Task.Factory.StartNew(async b => { var equeueShop = b as MoShopping; var equeueKey = $"{EnumHelper.EmDataKey.QiangOrderEqueue.ToString()}_{equeueShop.Id}"; var sbTaskLog = new StringBuilder(string.Empty); try { sbTaskLog.AppendFormat("商品【{0}-{1}】,开启抢购队列处理;", equeueShop.Name, equeueShop.Id); Console.WriteLine(sbTaskLog); //监控队列key是否存在 while (await _redis.KeyExists(equeueKey)) { //获取队列 var qiangOrder = await _redis.GetListAndPop(equeueKey); if (qiangOrder == null) { continue; } //获取真实剩余库存 var equShop = await _redis.GetHashField(shopsKey, equeueShop.Id.ToString()); if (equShop == null) { continue; } var sbLog = new StringBuilder(string.Empty); Stopwatch watch = new Stopwatch(); watch.Start(); try { #region 逻辑处理库存 sbLog.AppendFormat("用户:{0}抢购商品【{1}-{4}】当前库存:{2}件,抢购数:{3}件,", qiangOrder.UserId, equShop.Name, equShop.MaxNum, qiangOrder.Num, equShop.Id); if (equShop.MaxNum <= 0) { //无库存,直接抢购失败 qiangOrder.OrderStatus = (int)EnumHelper.EmOrderStatus.抢购失败; } else if (equShop.MaxNum < qiangOrder.Num) { //剩余库存小于抢购数量 qiangOrder.OrderStatus = (int)EnumHelper.EmOrderStatus.抢购失败; } else if (equShop.MaxGouNum < qiangOrder.Num) { //最大允许抢购数量小于抢购申请数量 qiangOrder.OrderStatus = (int)EnumHelper.EmOrderStatus.抢购失败; } else { //库存充足 equShop.MaxNum = equShop.MaxNum - qiangOrder.Num; //扣除当前抢购数量后,更新库存 var isOk = await _redis.SetOrUpdateHashsField(shopsKey, equShop.Id.ToString(), equShop, false) > 0; if (!isOk) {


网友评论