Ejemplo n.º 1
0
 public HomeController(RabbitMQConnectionService service)
 {
     _service = service;
 }
        public async Task <IActionResult> BuyAsync(int pId, int sId, CancellationToken cancellationToken)
        {
            // 初始化抢购信息
            if (!IsInit)
            {
                var sales = (await _saleService.GetSales()).ToList();

                for (int i = 0; i < sales.Count(); i++)
                {
                    _redisDb.StringSet($"{SalePrefix}{sales[i].PId}", sales[i].SaleCount);
                }
                IsInit = true;
            }

            string userId = Guid.NewGuid().ToString("N");
            int    stock  = Convert.ToInt32(_redisDb.StringGet($"{SalePrefix}{pId}"));

            if (stock <= 0)
            {
                return(CreateResult(false, "已售完!"));
            }

            DataProvider.Entities.Order order = await _orderService.FindUserSaleOrderAsync(userId, pId, sId);

            if (order != null)
            {
                return(CreateResult(false, "请勿重复抢购!"));
            }

            RabbitMQConnectionService rabbitMQConnectionService = new RabbitMQConnectionService();

            order = new DataProvider.Entities.Order()
            {
                CreationTime = DateTime.Now,
                PId          = pId,
                UserId       = userId,
                SId          = sId
            };

            using (var conn = rabbitMQConnectionService.GetConnection())
            {
                // 创建通道
                using var channel = conn.CreateModel();
                string exchangeName = "order";
                string routeKey     = "sendOrder";

                ///
                //channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, false, false);
                ////声明一个队列
                //channel.QueueDeclare("saleQueue", false, false, false);

                //channel.QueueBind("saleQueue", exchangeName, routeKey, null);

                // 定义发送内容
                string input = JsonConvert.SerializeObject(order);

                var sendBytes = Encoding.UTF8.GetBytes(input);

                channel.BasicPublish(exchangeName, routeKey, null, sendBytes);
            }

            return(CreateResult(true, "排队中..."));
        }