Files
QuestionLibraryMQConsumer/.trae/documents/.NET_MQ_Consumer_Project_Plan.md
2026-05-18 17:08:35 +08:00

3.7 KiB

QuestionLibraryMQConsumer 项目搭建计划

项目概述

搭建一个基于 .NET 8 的 RabbitMQ 消费者服务,用于消费题库相关的消息队列消息。

技术选型

  • .NET 8 - 最新 LTS 版本
  • Worker Service - 后台服务模板,适合 MQ 消费者场景
  • RabbitMQ.Client 7.x - 官方 RabbitMQ .NET 客户端
  • Serilog - 结构化日志
  • Microsoft.Extensions.Hosting - 依赖注入和配置管理
  • System.Text.Json - JSON 消息序列化

项目结构

QuestionLibraryMQConsumer/
├── QuestionLibraryMQConsumer.sln
├── src/
│   └── QuestionLibraryMQConsumer/
│       ├── QuestionLibraryMQConsumer.csproj
│       ├── Program.cs
│       ├── appsettings.json
│       ├── appsettings.Development.json
│       ├── Consumers/
│       │   └── QuestionMessageConsumer.cs
│       ├── Services/
│       │   └── IMessageProcessor.cs
│       │   └── QuestionMessageProcessor.cs
│       ├── Models/
│       │   └── QuestionMessage.cs
│       ├── Configuration/
│       │   └── RabbitMqOptions.cs
│       └── Extensions/
│           └── ServiceCollectionExtensions.cs
└── .gitignore

实施步骤

第一步: 创建 .NET 8 Worker Service 项目

  1. 创建解决方案文件
  2. 创建 Worker Service 项目
  3. 添加必要的 NuGet 包:
    • RabbitMQ.Client
    • Serilog.AspNetCore
    • Serilog.Sinks.Console
    • Serilog.Sinks.File
    • Microsoft.Extensions.Hosting

第二步: 创建配置模型

  1. 创建 RabbitMqOptions.cs - MQ 连接配置
    • Host: RabbitMQ 服务器地址
    • Port: 端口号 (默认 5672)
    • UserName: 用户名
    • Password: 密码
    • VirtualHost: 虚拟主机
    • QueueName: 队列名称
    • ExchangeName: 交换机名称
    • RoutingKey: 路由键
    • PrefetchCount: 预取数量
    • ConsumerCount: 消费者数量

第三步: 创建消息模型

  1. 创建 QuestionMessage.cs - 题库消息数据模型
    • MessageId: 消息 ID
    • QuestionId: 题目 ID
    • Action: 操作类型 (Add/Update/Delete)
    • Content: 消息内容
    • Timestamp: 时间戳
    • 其他题库相关字段

第三步: 创建消息处理器

  1. 创建 IMessageProcessor.cs - 消息处理接口
  2. 创建 QuestionMessageProcessor.cs - 具体实现
    • 实现消息处理逻辑
    • 支持重试机制
    • 记录处理日志

第四步: 创建消费者服务

  1. 创建 QuestionMessageConsumer.cs - 继承 BackgroundService
    • 实现 RabbitMQ 连接和通道管理
    • 注册消费者
    • 处理消息投递
    • 手动 ACK 确认
    • 处理异常和死信
    • 实现优雅关闭

第五步: 配置依赖注入

  1. 创建 ServiceCollectionExtensions.cs
    • 注册 RabbitMQ 配置
    • 注册消息处理器
    • 注册消费者服务

第六步: 创建主程序入口

  1. 修改 Program.cs
    • 配置主机
    • 加载配置
    • 注册服务
    • 配置 Serilog 日志

第七步: 创建配置文件

  1. 创建 appsettings.json - 默认配置
  2. 创建 appsettings.Development.json - 开发环境配置
  3. 创建 .gitignore - Git 忽略文件

第八步: 验证项目

  1. 执行 dotnet build 确保编译通过
  2. 验证项目结构完整性

关键设计决策

  1. 手动 ACK - 确保消息不丢失,处理成功后才确认
  2. Prefetch 限制 - 设置合理的预取数量,避免内存溢出
  3. 连接恢复 - 使用 RabbitMQ.Client 的自动恢复机制
  4. 优雅关闭 - 在应用停止时正确关闭消费者和连接
  5. 结构化日志 - 使用 Serilog 记录详细日志,便于排查问题
  6. 配置外部化 - 所有 MQ 配置通过配置文件管理