Mico.Demo/MicoService.Demo/Services/OrderInventoryNotificationS...

114 lines
4.2 KiB
C#

using MassTransit;
using MassTransit.Message;
using MicoService.Demo.DTOs;
namespace MicoService.Demo.Services
{
/// <summary>
/// Point-to-Point 通信模式示例 - 发送服务实现
/// </summary>
public class OrderInventoryNotificationService : IOrderInventoryNotificationService
{
private readonly ILogger<OrderInventoryNotificationService> _logger;
private readonly IBus _bus;
/// <summary>
/// 构造函数注入依赖
/// </summary>
public OrderInventoryNotificationService(ILogger<OrderInventoryNotificationService> logger, IBus bus)
{
_logger = logger;
_bus = bus;
}
/// <summary>
/// 发送订单创建通知(不等待响应)
/// </summary>
/// <param name="orderId">订单ID</param>
/// <param name="userId">用户ID</param>
/// <param name="items">订单项列表</param>
/// <returns>异步任务</returns>
public async Task SendOrderCreatedNotificationAsync(string orderId, string userId, List<OrderItemResponseDto> items)
{
_logger.LogInformation(
"[Point-to-Point Example] 发送订单 {OrderId} 的创建通知 (用户ID: {UserId})",
orderId, userId);
try
{
// 构建通知消息
var notification = new OrderInventoryNotificationRequest(
correlationId: orderId,
notificationType: "OrderCreated",
products: items.Select(item => new ProductInfo(
productId: item.ProductId,
productName: item.ProductName,
quantity: item.Quantity,
reason: "订单创建扣减库存"
)).ToList()
);
// 发送消息(不等待响应)
// IBus.Send() 是单向的,发送后立即返回
await _bus.Send(notification);
_logger.LogInformation(
"[Point-to-Point Example] 订单 {OrderId} 的创建通知已发送",
orderId);
}
catch (Exception ex)
{
_logger.LogError(ex,
"[Point-to-Point Example] 发送订单 {OrderId} 的创建通知失败",
orderId);
// 可以选择将失败的消息发送到死信队列或重试队列
throw;
}
}
/// <summary>
/// 发送订单取消通知(不等待响应)
/// </summary>
/// <param name="orderId">订单ID</param>
/// <param name="userId">用户ID</param>
/// <param name="items">订单项列表</param>
/// <returns>异步任务</returns>
public async Task SendOrderCancelledNotificationAsync(string orderId, string userId, List<OrderItemResponseDto> items)
{
_logger.LogInformation(
"[Point-to-Point Example] 发送订单 {OrderId} 的取消通知 (用户ID: {UserId})",
orderId, userId);
try
{
// 构建通知消息
var notification = new OrderInventoryNotificationRequest(
correlationId: orderId,
notificationType: "OrderCancelled",
products: items.Select(item => new ProductInfo(
productId: item.ProductId,
productName: item.ProductName,
quantity: item.Quantity,
reason: "订单取消恢复库存"
)).ToList()
);
// 发送消息(不等待响应)
await _bus.Send(notification);
_logger.LogInformation(
"[Point-to-Point Example] 订单 {OrderId} 的取消通知已发送",
orderId);
}
catch (Exception ex)
{
_logger.LogError(ex,
"[Point-to-Point Example] 发送订单 {OrderId} 的取消通知失败",
orderId);
throw;
}
}
}
}