using MassTransit; using MassTransit.Message; using MicoService.Demo.DTOs; namespace MicoService.Demo.Services { /// /// Point-to-Point 通信模式示例 - 发送服务实现 /// public class OrderInventoryNotificationService : IOrderInventoryNotificationService { private readonly ILogger _logger; private readonly IBus _bus; /// /// 构造函数注入依赖 /// public OrderInventoryNotificationService(ILogger logger, IBus bus) { _logger = logger; _bus = bus; } /// /// 发送订单创建通知(不等待响应) /// /// 订单ID /// 用户ID /// 订单项列表 /// 异步任务 public async Task SendOrderCreatedNotificationAsync(string orderId, string userId, List 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; } } /// /// 发送订单取消通知(不等待响应) /// /// 订单ID /// 用户ID /// 订单项列表 /// 异步任务 public async Task SendOrderCancelledNotificationAsync(string orderId, string userId, List 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; } } } }