示例#1
0
        /// <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);
        }