예제 #1
0
        public async Task <string> CreateOrder2([FromQuery] string goodsName, [FromQuery] string customerName, [FromQuery] Int64 amount)
        {
            var form = new CreateOrderSagaData
            {
                CreateOrder = new order_service.CreateOrderRequest
                {
                    CustomerName = customerName,
                    GoodsName    = goodsName,
                    Amount       = amount
                }
            };

            // TODO: 把sagaContext和start/commit/rollback玻璃出来,业务代码简单写就可以了
            using (var sagaContext = new SagaContext(_sagaCollaborator, _logger))
            {
                try
                {
                    await sagaContext.Start(form);

                    sagaContext.Bind(); // 把saga session绑定到当前async上下文中
                    await _createOrderSaga.createOrder(form);

                    await _createOrderSaga.reserveCustomer(form);

                    await _createOrderSaga.addLockedBalanceToMerchant(form);

                    await _createOrderSaga.approveOrder(form);

                    await _createOrderSaga.approveAddLockedBalanceToMerchant(form);

                    await _createOrderSaga.addOrderHistory(form);

                    // 也可以在这里加上其他各种业务逻辑

                    await sagaContext.Commit();

                    return(form.OrderId);
                }
                catch (Exception e)
                {
                    _logger.LogError("CreateOrder2 error", e);
                    await sagaContext.Rollback();

                    if (form.RejectionReason != null)
                    {
                        return(form.RejectionReason.ToString());
                    }
                    return(e.Message);
                }
            }
        }