public void Execute(IJobExecutionContext context) { var stopwatch = new Stopwatch(); Logger.Info("限时抢购销售数量同步开始"); stopwatch.Start(); var saleProducts = DalFlashSale.SelectFlashSaleProductModel().ToList(); var count = 0; foreach (var item in saleProducts) { using (var client = CacheHelper.CreateCounterClient($"test_{DateTime.Now.Date:yyyy_MM_dd}", TimeSpan.FromDays(30))) { var record = client.Count(item.ActivityId + item.Pid); if (record.Success) { item.Num = (int)record.Value; var result = DalFlashSale.UpdateFlashSaleProducts(item); if (result <= 0) { Logger.Error($"限时抢购销售数量同步失败:活动id=>{item.ActivityId}产品id=>{item.Pid}数量=>{item.Num}"); } else { count++; } } } } Logger.Error($"限时抢购销售数量同步完成消耗时间=>{stopwatch.ElapsedMilliseconds}共同步{count}条数据"); stopwatch.Stop(); }
public static async Task <OrderCountResponse> SetUserCreateFlashOrderCountCacheAsync( OrderCountCacheRequest request) { var keyModels = SetKeys(request); var flashSale = await DalFlashSale.FetchFlashSaleProductModel(new OrderItems() { PID = request.Pid, ActivityId = new Guid(request.ActivityId) }); var response = new OrderCountResponse(); using (var client = CacheHelper.CreateCounterClient(ClientName)) { //Queryable<int> personSorts = new Queryable[4, 5, 6]; //个人限购 if (flashSale.MaxQuantity.HasValue) { foreach (var key in keyModels.OrderBy(r => r.Sort).Where(r => r.Sort == 4 || r.Sort == 5 || r.Sort == 6)) { response = await SetCountValue(response, key.Key, request.PerSonalNum, client); if (response.RedisField) { break; } } } //会场限购 if (flashSale.PlaceQuantity.HasValue && flashSale.PlaceQuantity.Value > 0) { var saleProducts = (await DalFlashSale.SelectFlashSaleFromDBAsync(new Guid(request.ActivityId))).Products.ToList(); var salePids = saleProducts.Where(r => r.IsJoinPlace).Select(r => r.PID).ToList(); if (salePids.Contains(request.Pid)) { foreach (var key in keyModels.OrderBy(r => r.Sort).Where(r => r.Sort == 1 || r.Sort == 2 || r.Sort == 3)) { response = await SetCountValue(response, key.Key, request.PlaceNum, client); if (response.RedisField) { break; } } } } } if (response.RedisField) { return(response); } return(await GetUserCreateFlashOrderCountCacheAsync(request)); }
public static async Task <OrderCountResponse> GetUserCreateFlashOrderCountCacheAsync( OrderCountCacheRequest request) { var responseModel = new OrderCountResponse(); var keyModels = SetKeys(request); using (var client = CacheHelper.CreateCounterClient(ClientName)) { foreach (var key in keyModels.OrderBy(r => r.Sort)) { await GetCountValue(responseModel, key.Type, key.Key, client); //if(result.RedisField) // break; } } var flashsale = (await DalFlashSale.SelectFlashSaleFromDBAsync(new Guid(request.ActivityId))); if (flashsale == null) { return(responseModel); } var saleProducts = flashsale.Products.ToList(); var salePids = saleProducts.Where(r => r.IsJoinPlace).Select(r => r.PID).ToList(); var saleproduct = saleProducts.FirstOrDefault(r => r.PID == request.Pid); var records = (await DalFlashSale.SelectOrderActivityProductOrderRecordsAsync( new Guid(request.UserId), request.DeviceId, new Guid(request.ActivityId), request.UserTel)).ToList(); var personQty = records?.Where(r => r.PID == request.Pid).Sum(r => r.Quantity) ?? 0; var placeQty = records.Where(r => salePids.Contains(r.PID)).Sum(r => r.Quantity); responseModel.UserDbPersonLimitQty = personQty; responseModel.UserDbPlaceLimitQty = placeQty; responseModel.PersonConfigLimitQty = saleproduct?.MaxQuantity; responseModel.PlaceConfigLimitQty = saleproduct?.PlaceQuantity; responseModel.TotalConfigQty = saleproduct?.TotalQuantity; return(responseModel); }
public void RefreshAllPids() { try { Logger.Info($"开始刷新"); var datas = DalFlashSale.SelectAllSaleActivity() ?? new List <Models.FlashSaleProductModel>(); Logger.Info($"总数:{datas.Count}"); if (!datas.Any()) { return; } var pidCacheHour = 12; // pid缓存小时数 var prefixCacheHour = 12; //前缀缓存小时数 var index = 0; var productInterface = new ProductInterface(Logger); var prefix = (DateTime.Now - DateTime.MinValue).TotalMilliseconds.ToString(); var errorPids = new List <string>(); datas.Select(r => r.Pid).Split(100).Select(p => p.ToList()) .ForEach(pids => { errorPids.AddRange( AsyncHelper.RunSync( () => productInterface.RefreshProductSaleActivityCacheByPidsWithPrefixAsync( pids, prefix, pidCacheHour))); Logger.Info($"第{++index}批刷新完成"); Thread.Sleep(50); }); Logger.Info($"刷新完成,失败数:{errorPids.Count}"); var result = AsyncHelper.RunSync( () => productInterface.ResetPrefixForProductSaleActivityCacheByPidsCacheAsync( prefix, prefixCacheHour)); Logger.Info($"重置缓存-->result:{result}"); } catch (Exception e) { Logger.Error($"刷新异常", e); } }
public Task <OperationResult <int> > DeleteFlashSaleRecordsAsync(int orderId) => OperationResult.FromResultAsync <int>(DalFlashSale.DeleteFlashSaleRecordsAsync(orderId));
/// <summary> /// 获取当前用户的购买数量 /// </summary> /// <param name="userId">用户ID</param> /// <returns></returns> public async Task <int?> GetCurrentUserPurchaseCount(string id, string type) { int?result = null; if (string.IsNullOrEmpty(id)) { return(0); } string key = GetUserKey(id, type); var dataInCache = await _counter.GetAsync <int>(new List <string>() { key }); if (dataInCache.Success) { if (dataInCache.Value != null && dataInCache.Value.Any()) { result = dataInCache.Value.First().Value; } else { IEnumerable <int> orderIds = null; switch (type) { case "userId": orderIds = await DalFlashSale.SelectFlashSaleOrderIdsByUserAsync(_activityId, Guid.Parse(id), Guid.NewGuid().ToString(), string.Empty); break; case "deviceId": orderIds = await DalFlashSale.SelectFlashSaleOrderIdsByUserAsync(_activityId, Guid.Empty, id, string.Empty); break; case "userTel": orderIds = await DalFlashSale.SelectFlashSaleOrderIdsByUserAsync(_activityId, Guid.Empty, Guid.NewGuid().ToString(), id); break; } var count = 0; if (orderIds != null && orderIds.Any()) { count = orderIds.Distinct().Count(); } var increResult = await _counter.IncrementAsync(key, count); if (increResult.Success) { if (increResult.Value > count) { bool decResult = await RetryDecrement(key, count); } else { result = count; } } else { _logger.Error($"计数器设置失败, id: {id}, type: {type}, {dataInCache.Message}", dataInCache.Exception); } } } else { _logger.Error($"计数器获取失败, {dataInCache.Message}", dataInCache.Exception); } return(result); }
public async Task <int?> GetCurrentActivityPurchaseCount() { int?result = null; string key = GetActivityKey(); var dataInCache = await _counter.GetAsync <int>(new List <string>() { key }); if (dataInCache.Success) { if (dataInCache.Value != null && dataInCache.Value.Any()) { result = dataInCache.Value.First().Value; } else { using (var zlock = new ZooKeeperLock(key)) { if (await zlock.WaitAsync(1500)) { var retryGet = await _counter.GetAsync <int>(new List <string>() { key }); if (retryGet.Success && retryGet.Value != null && retryGet.Value.Any()) { result = retryGet.Value.First().Value; } else { var orderIds = await DalFlashSale.SelectFlashSaleOrderIdsByActivityAsync(_activityId, _round.StartTime, _round.EndTime); var count = 0; if (orderIds != null && orderIds.Any()) { var orderStatus = await DalFlashSale.SelectOrderStatusByOrderIdsAsync(orderIds); count = orderStatus.Where(o => !string.Equals(o.Value, "7Canceled")).Count(); } var increResult = await _counter.IncrementAsync(key, count); if (increResult.Success) { if (increResult.Value > count) { bool decResult = await RetryDecrement(key, count); } else { result = count; } } else { _logger.Error($"计数器设置失败, activity: {_activityId}, {dataInCache.Message}", dataInCache.Exception); } } } } } } else { _logger.Error($"计数器获取失败, {dataInCache.Message}", dataInCache.Exception); } return(result); }
private static async Task <CheckFlashSaleResponseModel> CheckFlashSaleByPidAsync(OrderItems item, Guid userId, string deviceId, string userTel) { var hasMaxLimit = false; var hasPlaceLimit = false; string allPlaceLimitId = null; try { if (!item.ActivityId.HasValue) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.NoExist, } } ; var flashSale = await DalFlashSale.FetchFlashSaleProductModel(item); if (flashSale == null) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.NoExist, }); } var model = await FlashSaleCounter.RedisHashRecord(item.PID, item); if (model.Code == CheckFlashSaleStatus.CreateOrderFailed) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, } } ; var record = model.Record; var remainQuantity = flashSale.TotalQuantity - record; if (remainQuantity < 0) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.NoEnough, } } ; var request = new GenerateKeyRequest { DeviceId = deviceId, UserId = userId.ToString(), UserTel = userTel, ActivityId = item.ActivityId.ToString(), Pid = item.PID }; var countKey = new GenerateFlashSaleKey(request); if (flashSale.MaxQuantity.HasValue) { var personLimit1 = await FlashSaleCounter.RedisCounterRecord(countKey.PersonalkeyUserId, LimitType.PersonalLimit, CounterKeyType.UserIdKey, item, userId, deviceId, userTel, null, -1); if (personLimit1.Code < 0) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, } } ; var personLimit2 = await FlashSaleCounter.RedisCounterRecord(countKey.PersonalkeyDeviceId, LimitType.PersonalLimit, CounterKeyType.DeviceIdKey, item, userId, deviceId, userTel, null, personLimit1.DeviceCount); if (personLimit2.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PersonalkeyUserId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } var personLimit3 = await FlashSaleCounter.RedisCounterRecord(countKey.PersonalkeyUseTel, LimitType.PersonalLimit, CounterKeyType.UserTelKey, item, userId, deviceId, userTel, null, personLimit1.TelCount); if (personLimit3.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PersonalkeyUserId); await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PersonalkeyDeviceId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } if (personLimit1.Code < 0 || personLimit2.Code < 0 || personLimit3.Code < 0) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } var maxLimit = Math.Max(Math.Max(personLimit1.Record, personLimit2.Record), personLimit3.Record); hasMaxLimit = true; if (maxLimit > flashSale.MaxQuantity) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.MaxQuantityLimit, HasQuantityLimit = true }); } } if (flashSale.PlaceQuantity.HasValue && flashSale.PlaceQuantity.Value > 0) { var saleProducts = (await DalFlashSale.SelectFlashSaleProductsAsync(item.ActivityId.Value)).ToList(); var salePids = saleProducts.Where(r => r.IsJoinPlace).Select(r => r.PID).ToList(); if (salePids.Contains(item.PID)) { var placeLimit1 = await FlashSaleCounter.RedisCounterRecord(countKey.PlacekeyUserId, LimitType.PlaceLimit, CounterKeyType.UserIdKey, item, userId, deviceId, userTel, salePids, -1); if (placeLimit1.Code < 0) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, } } ; var placeLimit2 = await FlashSaleCounter.RedisCounterRecord(countKey.PlacekeyDeviceId, LimitType.PlaceLimit, CounterKeyType.DeviceIdKey, item, userId, deviceId, userTel, salePids, placeLimit1.DeviceCount); if (placeLimit2.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PlacekeyUserId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } var placeLimit3 = await FlashSaleCounter.RedisCounterRecord(countKey.PlacekeyUseTel, LimitType.PlaceLimit, CounterKeyType.UserTelKey, item, userId, deviceId, userTel, salePids, placeLimit1.TelCount); if (placeLimit3.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PlacekeyUserId); await FlashSaleCounter.DecrementCountCount(orderItem, countKey.PlacekeyDeviceId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } if (placeLimit1.Code < 0 || placeLimit2.Code < 0 || placeLimit3.Code < 0) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } hasPlaceLimit = true; var placeLimit = Math.Max(Math.Max(placeLimit1.Record, placeLimit2.Record), placeLimit3.Record); if (placeLimit > flashSale.PlaceQuantity.Value) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.PlaceQuantityLimit, HasQuantityLimit = hasMaxLimit, HasPlaceLimit = true }); } } } #region 针对618增加一个全局会场限购 if (flashSale.ActiveType == 3 && FlashSaleManager.CheckAllPlaceLimitStatrtDate()) { var allPLimitId = GlobalConstant.AllPlaceLimitId; item.AllPlaceLimitId = allPLimitId; var request1 = new GenerateKeyRequest { DeviceId = deviceId, UserId = userId.ToString(), UserTel = userTel, ActivityId = item.AllPlaceLimitId, Pid = item.PID, IsAllPlaceLimit = true }; var countKeyAllLimit = new GenerateFlashSaleKey(request1); var config = await FlashSaleManager.SelectFlashSaleDataByActivityIDAsync(new Guid(allPLimitId)); if (config.PlaceQuantity.HasValue) { var saleProducts = config.Products.ToList(); var salePids = saleProducts.Where(r => r.IsJoinPlace).Select(r => r.PID).ToList(); if (salePids.Contains(item.PID)) { var placeLimit1 = await FlashSaleCounter.RedisCounterRecord( countKeyAllLimit.PlacekeyUserId, LimitType.AllPlaceLimit, CounterKeyType.UserIdKey, item, userId, deviceId, userTel, salePids, -1); if (placeLimit1.Code < 0) { return new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, } } ; var placeLimit2 = await FlashSaleCounter.RedisCounterRecord(countKeyAllLimit.PlacekeyDeviceId, LimitType.AllPlaceLimit, CounterKeyType.DeviceIdKey, item, userId, deviceId, userTel, salePids, placeLimit1.DeviceCount); if (placeLimit2.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKeyAllLimit.PlacekeyUserId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } var placeLimit3 = await FlashSaleCounter.RedisCounterRecord(countKeyAllLimit.PlacekeyUseTel, LimitType.AllPlaceLimit, CounterKeyType.UserTelKey, item, userId, deviceId, userTel, salePids, placeLimit1.TelCount); if (placeLimit3.Code < 0) { var orderItem = new CheckFlashSaleResponseModel { Num = item.Num }; await FlashSaleCounter.DecrementCountCount(orderItem, countKeyAllLimit.PlacekeyUserId); await FlashSaleCounter.DecrementCountCount(orderItem, countKeyAllLimit.PlacekeyDeviceId); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } if (placeLimit1.Code < 0 || placeLimit2.Code < 0 || placeLimit3.Code < 0) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, }); } var allplaceLimit = Math.Max(Math.Max(placeLimit1.Record, placeLimit2.Record), placeLimit3.Record); allPlaceLimitId = allPLimitId; if (allplaceLimit > config.PlaceQuantity.Value) { return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.PlaceQuantityLimit, AllPlaceLimitId = allPlaceLimitId }); } } #region 错误代码 //var hashRecord618 = await FlashSaleCounter.RedisAllPlaceLimitHashRecord(item.PID, item); //if (hashRecord618 != null) //{ // if (hashRecord618.Code == CheckFlashSaleStatus.CreateOrderFailed) // return new CheckFlashSaleResponseModel() // { // Code = CheckFlashSaleStatus.CreateOrderFailed, // }; // var saledAll = model.Record; // var config = // await FlashSaleManager.SelectFlashSaleDataByActivityIDAsync( // new Guid(allPLimitId)); // var configQty = config.Products.Where(r => r.PID == item.PID).Select(r => r.TotalQuantity).FirstOrDefault(); // allPlaceLimitId = allPLimitId; // if (configQty - saledAll < 0) // return new CheckFlashSaleResponseModel() // { // Code = CheckFlashSaleStatus.NoEnough, // AllPlaceLimitId = allPlaceLimitId // }; //} #endregion } } #endregion return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.Succeed, HasPlaceLimit = hasPlaceLimit, HasQuantityLimit = hasMaxLimit, AllPlaceLimitId = allPlaceLimitId }); #endregion } catch (Exception ex) { Logger.Info(ex); return(new CheckFlashSaleResponseModel() { Code = CheckFlashSaleStatus.CreateOrderFailed, HasPlaceLimit = hasPlaceLimit, HasQuantityLimit = hasMaxLimit }); } }
public static async Task <IEnumerable <ActivityPriceModel> > FetchActivityProductPrice(ActivityPriceRequest request) { var data = request.Items.Where(g => !string.IsNullOrWhiteSpace(g.PID)) .GroupBy(g => g.ActicityId) .Select(g => new ProductActivityType { ActivityId = g.Key, PIDs = g.Select(t => t.PID).ToList() }); var result = new List <ActivityPriceModel>(); if (data.Any()) { var types = ActivityManager.SelectActivityTypeByActivityIds(data.Select(g => g.ActivityId).ToList()).Where(g => g != null); foreach (var item in data) { var type = types.FirstOrDefault(g => g.ActivityId == item.ActivityId); //拼团 if (type == null && await GroupBuyingManager.CheckProductGroupId(item.ActivityId)) { type = new ActivityTypeModel { ActivityId = item.ActivityId, Type = 7 }; } if (type == null) { continue; } if (type.Type == 1) { var dat = await DalBargain.SelectProductActivityPrice(item.ActivityId, item.PIDs); if (dat == null || dat.Count() != item.PIDs.Count) { return(null); } result.AddRange(dat); } else if (type.Type == 9) { if (request.UserId == Guid.Empty) { break; } var userId = request.UserId; foreach (var pid in item.PIDs) { result.Add(await DalBargain.FetchBargainPrice(pid, userId)); } } else if (type.Type == 7) { // 拼团 if (request.UserId == Guid.Empty) { break; } foreach (var pid in item.PIDs) { if (request.GroupId == Guid.Empty) { var priceInfo = await DalFlashSale.FetchGroupBuyingPrtoductPrice(item.ActivityId, pid, Logger); if (await DalFlashSale.CheckFreeCouponInfo(item.ActivityId, request.UserId)) { priceInfo.ActivityPrice = 0; Logger.Info($"GroupBuyingFreeCoupon==>{request.UserId:D}/{item.ActivityId:D}/{pid}==>符合团长免单==>活动价为0"); } result.Add(priceInfo); } else { var dat = await DalFlashSale.FetchGroupBuyingPrice(pid, request.UserId, request.GroupId, Logger); if (dat.Code == 0) { return(null); } result.Add(dat); } } } } } return(result); }
/// <summary> /// 记录购买记录进计数器 /// </summary> /// <param name="key"></param> /// <param name="item"></param> /// <returns></returns> public static async Task <SimpleResponseModel> RedisHashRecord(string key, OrderItems item) { using (var client = CacheHelper.CreateHashClient(item.ActivityId.ToString(), TimeSpan.FromDays(30))) { var recordCache = await client.GetAsync <int>(key); double retryresult = 0; IResult <double> increment; var incrementNum = 0; if (!recordCache.Success) { if (recordCache.Message == "Key不存在") //暂时写死错误信息,后面如果底层针对这种情况有固定errorcode返回修改下 { if (item.ActivityId.ToString() == "c6cc9628-21aa-4f85-a19c-fd12529159e8") //买三送一活动打log { Logger.Info($"hash缓存加之前=》Key{key}value{recordCache.Value}活动id:{item.ActivityId.ToString()}"); } var result = await DalFlashSale.FetchFlashSaleProductModel(item); var quantity = result.SaleOutQuantity; increment = await client.IncrementAsync(key, quantity + item.Num); incrementNum = quantity + item.Num; } else { Logger.Error($"redis计数记录失败=>CheckFlashSaleAsync{key}"); return(new SimpleResponseModel { Code = CheckFlashSaleStatus.CreateOrderFailed, Mesage = "计数器执行失败" }); } } else { increment = await client.IncrementAsync(key, item.Num); incrementNum = item.Num; } if (!increment.Success) //失败情况后续考虑 { retryresult = await RedisCountRetry(() => client.IncrementAsync(key, incrementNum)); if (retryresult < 0) { Logger.Error($"redis计数记录失败=>CheckFlashSaleAsync{key}"); return(new SimpleResponseModel { Code = CheckFlashSaleStatus.CreateOrderFailed, Mesage = "计数器执行失败" }); } } if (item.ActivityId.ToString() == "c6cc9628-21aa-4f85-a19c-fd12529159e8") //买三送一活动打log { Logger.Info($"hash缓存加之后=》Key:{key}value:{increment.Value}活动id:{item.ActivityId.ToString()}"); } return(new SimpleResponseModel { Code = CheckFlashSaleStatus.Succeed, Record = (int)(increment.Success ? increment.Value : retryresult), Mesage = "成功" }); } }
public static async Task <SimpleResponseModel> RedisCounterRecord(string key, LimitType type, CounterKeyType keyType, OrderItems item, Guid userId = new Guid(), string deviceId = null, string userTel = null, List <string> pids = null, int dbQuantity = 0) { Logger.Info($"计数器Key=>{key}增加{item.Num}"); using (var client = CacheHelper.CreateCounterClient(ClientName, TimeSpan.FromDays(30))) { var recordCache = await client.CountAsync(key); //这里跟hashclient一点咯要区分开,这里key不存在会报错 double retryresult = 0; IResult <long> increment; var tupleReult = new Tuple <int, int, int>(0, -1, -1); var incrementNum = 0; var quantity = dbQuantity; if (!recordCache.Success) { if (recordCache.Message == "Key不存在") //暂时写死错误信息,后面如果底层针对这种情况有固定errorcode返回修改下 { if (dbQuantity == -1) { switch (type) { case LimitType.PlaceLimit: if (item.ActivityId != null) { tupleReult = await DalFlashSale.SelectOrderActivityProductRecordNumAsync( userId, deviceId, string.IsNullOrEmpty(item.AllPlaceLimitId)?item.ActivityId.Value : new Guid(item.AllPlaceLimitId), userTel, pids); quantity = GetDbQtyBykeyType(tupleReult, keyType, deviceId); } break; case LimitType.PersonalLimit: if (item.ActivityId != null) { tupleReult = await DalFlashSale.SelectOrderActivityProductRecordNumAsync(userId, deviceId, item.ActivityId.Value, userTel, new List <string> { item.PID }); quantity = GetDbQtyBykeyType(tupleReult, keyType, deviceId); } break; case LimitType.AllPlaceLimit: if (item.ActivityId != null) { tupleReult = await DalFlashSale.SelectAllPlaceOrderActivityProductRecordNumAsync( userId, deviceId, new Guid(item.AllPlaceLimitId), userTel, pids); quantity = GetDbQtyBykeyType(tupleReult, keyType, deviceId); } break; } } increment = await client.IncrementAsync(key, quantity + item.Num); incrementNum = quantity + item.Num; } else { Logger.Error($"redis计数记录失败=>CheckFlashSaleAsync{key}"); return(new SimpleResponseModel { Code = CheckFlashSaleStatus.CreateOrderFailed, Mesage = "计数器执行失败" }); } } else { increment = await client.IncrementAsync(key, item.Num); incrementNum = item.Num; } if (!increment.Success) //失败情况后续考虑 { retryresult = await RedisCountRetry(() => client.IncrementAsync(key, incrementNum)); if (retryresult < 0) { Logger.Error($"redis计数记录失败=>CheckFlashSaleAsync{key}"); return(new SimpleResponseModel { Code = CheckFlashSaleStatus.CreateOrderFailed, Mesage = "计数器执行失败" }); } } return(new SimpleResponseModel { Code = CheckFlashSaleStatus.Succeed, Record = (int)(increment.Success ? increment.Value : retryresult), Mesage = "成功", //DbQuantity = quantity, DeviceCount = tupleReult.Item2, TelCount = tupleReult.Item3 }); } }
public async Task <int?> GetCurrentActivityPurchaseCount() { int?result = null; var sw = new Stopwatch(); sw.Start(); long getCountCache = 0; long beforeLockTime = 0; long inLockTime = 0; long selectFlashSaleOrderIdsByActivityTime = 0; long selectOrderStatusByOrderIdsTime = 0; string key = GetActivityKey(); var dataInCache = await _counter.GetAsync <int>(new List <string>() { key }); getCountCache = sw.ElapsedMilliseconds; if (dataInCache.Success) { if (dataInCache.Value != null && dataInCache.Value.Any()) { result = dataInCache.Value.First().Value; } else { beforeLockTime = sw.ElapsedMilliseconds - getCountCache; using (var zlock = new ZooKeeperLock(key)) { if (await zlock.WaitAsync(1500)) { inLockTime = sw.ElapsedMilliseconds - beforeLockTime; var retryGet = await _counter.GetAsync <int>(new List <string>() { key }); if (retryGet.Success && retryGet.Value != null && retryGet.Value.Any()) { result = retryGet.Value.First().Value; } else { var orderIds = await DalFlashSale.SelectFlashSaleOrderIdsByActivityAsync(_activityId, _round.StartTime, _round.EndTime); selectFlashSaleOrderIdsByActivityTime = sw.ElapsedMilliseconds - inLockTime; var count = 0; if (orderIds != null && orderIds.Any()) { var orderStatus = await DalFlashSale.SelectOrderStatusByOrderIdsAsync(orderIds); selectOrderStatusByOrderIdsTime = sw.ElapsedMilliseconds - selectFlashSaleOrderIdsByActivityTime; count = orderStatus.Where(o => !string.Equals(o.Value, "7Canceled")).Count(); } var increResult = await _counter.IncrementAsync(key, count); if (increResult.Success) { if (increResult.Value > count) { bool decResult = await RetryDecrement(key, count); } else { result = count; } } else { _logger.Error($"计数器设置失败, activity: {_activityId}, {dataInCache.Message}", dataInCache.Exception); } } } } } } else { _logger.Error($"计数器获取失败, {dataInCache.Message}", dataInCache.Exception); } _logger.Info($"GetCurrentActivityPurchaseCount=>getCountCache:{getCountCache}," + $"beforeLockTime:{beforeLockTime},inLockTime:{inLockTime}," + $"selectFlashSaleOrderIdsByActivityTime:{selectFlashSaleOrderIdsByActivityTime}," + $"selectOrderStatusByOrderIdsTime:{selectOrderStatusByOrderIdsTime}," + $"total:{sw.ElapsedMilliseconds}"); sw.Stop(); return(result); }