forked from datawhale/whale-town-end
- 优化主README.md的文件结构总览,采用总分结构设计 - 大幅改进docs/ARCHITECTURE.md,详细说明业务功能模块化架构 - 新增docs/DOCUMENT_CLEANUP.md记录文档清理过程 - 更新docs/README.md添加新文档的导航链接 本次更新完善了项目文档体系,便于开发者快速理解项目架构
32 KiB
32 KiB
🏗️ Whale Town 项目架构设计
基于业务功能模块化的现代化后端架构,支持双模式运行,开发测试零依赖,生产部署高性能。
📋 目录
🎯 架构概述
Whale Town 采用业务功能模块化架构,将代码按业务功能而非技术组件组织,确保高内聚、低耦合的设计原则。
🌟 核心设计理念
- 业务驱动 - 按业务功能组织代码,而非技术分层
- 双模式支持 - 开发测试零依赖,生产部署高性能
- 清晰分层 - 业务层 → 核心层 → 数据层,职责明确
- 模块化设计 - 每个模块独立完整,可单独测试和部署
- 配置驱动 - 通过环境变量控制运行模式和行为
📊 整体架构图
┌─────────────────────────────────────────────────────────────────┐
│ 🌐 API接口层 │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🔗 REST API │ │ 🔌 WebSocket │ │ 📄 Swagger UI │ │
│ │ (HTTP接口) │ │ (实时通信) │ │ (API文档) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────────┐
│ 🎯 业务功能模块层 │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🔐 用户认证 │ │ 👥 用户管理 │ │ 🛡️ 管理员 │ │
│ │ (auth) │ │ (user-mgmt) │ │ (admin) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🔒 安全防护 │ │ 💬 Zulip集成 │ │ 🔗 共享组件 │ │
│ │ (security) │ │ (zulip) │ │ (shared) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────────┐
│ ⚙️ 核心技术服务层 │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🔑 登录核心 │ │ 👑 管理员核心 │ │ 💬 Zulip核心 │ │
│ │ (login_core) │ │ (admin_core) │ │ (zulip) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🛠️ 工具服务 │ │ 📧 邮件服务 │ │ 📝 日志服务 │ │
│ │ (utils) │ │ (email) │ │ (logger) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────────┐
│ 🗄️ 数据存储层 │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 🗃️ 数据库 │ │ 🔴 Redis缓存 │ │ 📁 文件存储 │ │
│ │ (MySQL/内存) │ │ (Redis/文件) │ │ (logs/data) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
📁 目录结构详解
🎯 业务功能模块 (src/business/)
设计原则: 按业务功能组织,每个模块包含完整的业务逻辑
src/business/
├── 📂 auth/ # 🔐 用户认证模块
│ ├── 📄 auth.controller.ts # HTTP接口控制器
│ ├── 📄 auth.service.ts # 业务逻辑服务
│ ├── 📄 auth.module.ts # 模块定义
│ ├── 📂 dto/ # 数据传输对象
│ │ ├── 📄 login.dto.ts # 登录请求DTO
│ │ ├── 📄 register.dto.ts # 注册请求DTO
│ │ └── 📄 reset-password.dto.ts # 重置密码DTO
│ └── 📂 __tests__/ # 单元测试
│ └── 📄 auth.service.spec.ts
│
├── 📂 user-mgmt/ # 👥 用户管理模块
│ ├── 📄 user-mgmt.controller.ts # 用户管理接口
│ ├── 📄 user-mgmt.service.ts # 用户状态管理逻辑
│ ├── 📄 user-mgmt.module.ts # 模块定义
│ ├── 📂 dto/ # 数据传输对象
│ │ ├── 📄 update-status.dto.ts # 状态更新DTO
│ │ └── 📄 batch-status.dto.ts # 批量操作DTO
│ └── 📂 enums/ # 枚举定义
│ └── 📄 user-status.enum.ts # 用户状态枚举
│
├── 📂 admin/ # 🛡️ 管理员模块
│ ├── 📄 admin.controller.ts # 管理员接口
│ ├── 📄 admin.service.ts # 管理员业务逻辑
│ ├── 📄 admin.module.ts # 模块定义
│ ├── 📂 dto/ # 数据传输对象
│ └── 📂 guards/ # 权限守卫
│ └── 📄 admin.guard.ts # 管理员权限验证
│
├── 📂 security/ # 🔒 安全防护模块
│ ├── 📄 security.module.ts # 安全模块定义
│ ├── 📂 guards/ # 安全守卫
│ │ ├── 📄 throttle.guard.ts # 频率限制守卫
│ │ ├── 📄 maintenance.guard.ts # 维护模式守卫
│ │ └── 📄 content-type.guard.ts # 内容类型守卫
│ └── 📂 interceptors/ # 拦截器
│ └── 📄 timeout.interceptor.ts # 超时拦截器
│
├── 📂 zulip/ # 💬 Zulip集成模块
│ ├── 📄 zulip.service.ts # Zulip业务服务
│ ├── 📄 zulip_websocket.gateway.ts # WebSocket网关
│ ├── 📄 zulip.module.ts # 模块定义
│ └── 📂 services/ # 子服务
│ ├── 📄 message_filter.service.ts # 消息过滤
│ └── 📄 session_cleanup.service.ts # 会话清理
│
└── 📂 shared/ # 🔗 共享业务组件
├── 📂 decorators/ # 装饰器
├── 📂 pipes/ # 管道
├── 📂 filters/ # 异常过滤器
└── 📂 interfaces/ # 接口定义
⚙️ 核心技术服务 (src/core/)
设计原则: 提供技术基础设施,支持业务模块运行
src/core/
├── 📂 db/ # 🗄️ 数据库层
│ ├── 📄 db.module.ts # 数据库模块
│ ├── 📂 users/ # 用户数据服务
│ │ ├── 📄 users.service.ts # MySQL数据库实现
│ │ ├── 📄 users-memory.service.ts # 内存数据库实现
│ │ ├── 📄 users.interface.ts # 用户服务接口
│ │ └── 📄 user.entity.ts # 用户实体定义
│ └── 📂 entities/ # 数据库实体
│ └── 📄 *.entity.ts # 各种实体定义
│
├── 📂 redis/ # 🔴 Redis缓存层
│ ├── 📄 redis.module.ts # Redis模块
│ ├── 📄 redis.service.ts # Redis真实实现
│ ├── 📄 file-redis.service.ts # 文件存储实现
│ └── 📄 redis.interface.ts # Redis服务接口
│
├── 📂 login_core/ # 🔑 登录核心服务
│ ├── 📄 login-core.service.ts # 登录核心逻辑
│ ├── 📄 login-core.module.ts # 模块定义
│ └── 📄 login-core.interface.ts # 接口定义
│
├── 📂 admin_core/ # 👑 管理员核心服务
│ ├── 📄 admin-core.service.ts # 管理员核心逻辑
│ ├── 📄 admin-core.module.ts # 模块定义
│ └── 📄 admin-core.interface.ts # 接口定义
│
├── 📂 zulip/ # 💬 Zulip核心服务
│ ├── 📄 zulip-core.module.ts # Zulip核心模块
│ ├── 📄 zulip-api.service.ts # Zulip API服务
│ └── 📄 zulip-websocket.service.ts # WebSocket服务
│
└── 📂 utils/ # 🛠️ 工具服务
├── 📂 email/ # 📧 邮件服务
│ ├── 📄 email.service.ts # 邮件发送服务
│ ├── 📄 email.module.ts # 邮件模块
│ └── 📄 email.interface.ts # 邮件接口
├── 📂 verification/ # 🔢 验证码服务
│ ├── 📄 verification.service.ts # 验证码生成验证
│ └── 📄 verification.module.ts # 验证码模块
└── 📂 logger/ # 📝 日志服务
├── 📄 logger.service.ts # 日志记录服务
└── 📄 logger.module.ts # 日志模块
🎨 前端管理界面 (client/)
设计原则: 独立的前端项目,提供管理员后台功能
client/
├── 📂 src/ # 前端源码
│ ├── 📂 components/ # 通用组件
│ │ ├── 📄 Layout.tsx # 布局组件
│ │ ├── 📄 UserTable.tsx # 用户表格组件
│ │ └── 📄 LogViewer.tsx # 日志查看组件
│ ├── 📂 pages/ # 页面组件
│ │ ├── 📄 Login.tsx # 登录页面
│ │ ├── 📄 Dashboard.tsx # 仪表板
│ │ ├── 📄 UserManagement.tsx # 用户管理
│ │ └── 📄 LogManagement.tsx # 日志管理
│ ├── 📂 services/ # API服务
│ │ ├── 📄 api.ts # API客户端
│ │ ├── 📄 auth.ts # 认证服务
│ │ └── 📄 users.ts # 用户服务
│ ├── 📂 utils/ # 工具函数
│ ├── 📂 types/ # TypeScript类型
│ ├── 📄 App.tsx # 应用主组件
│ └── 📄 main.tsx # 应用入口
├── 📂 dist/ # 构建产物
├── 📄 package.json # 前端依赖
├── 📄 vite.config.ts # Vite配置
└── 📄 tsconfig.json # TypeScript配置
📚 文档中心 (docs/)
设计原则: 完整的项目文档,支持开发者快速上手
docs/
├── 📄 README.md # 📖 文档导航中心
├── 📄 ARCHITECTURE.md # 🏗️ 架构设计文档
├── 📄 API_STATUS_CODES.md # 📋 API状态码说明
├── 📄 CONTRIBUTORS.md # 🤝 贡献者指南
│
├── 📂 api/ # 🔌 API接口文档
│ ├── 📄 README.md # API文档使用指南
│ ├── 📄 api-documentation.md # 完整API接口文档
│ ├── 📄 openapi.yaml # OpenAPI规范文件
│ └── 📄 postman-collection.json # Postman测试集合
│
├── 📂 development/ # 💻 开发指南
│ ├── 📄 backend_development_guide.md # 后端开发规范
│ ├── 📄 git_commit_guide.md # Git提交规范
│ ├── 📄 AI辅助开发规范指南.md # AI辅助开发指南
│ ├── 📄 TESTING.md # 测试指南
│ └── 📄 naming_convention.md # 命名规范
│
└── 📂 deployment/ # 🚀 部署文档
└── 📄 DEPLOYMENT.md # 生产环境部署指南
🧪 测试文件 (test/)
设计原则: 完整的测试覆盖,确保代码质量
test/
├── 📂 unit/ # 单元测试
├── 📂 integration/ # 集成测试
├── 📂 e2e/ # 端到端测试
└── 📂 fixtures/ # 测试数据
⚙️ 配置文件
设计原则: 清晰的配置管理,支持多环境部署
项目根目录/
├── 📄 .env # 🔧 环境变量配置
├── 📄 .env.example # 🔧 环境变量示例
├── 📄 .env.production.example # 🔧 生产环境示例
├── 📄 package.json # 📋 项目依赖配置
├── 📄 pnpm-workspace.yaml # 📦 pnpm工作空间配置
├── 📄 tsconfig.json # 📘 TypeScript配置
├── 📄 jest.config.js # 🧪 Jest测试配置
├── 📄 nest-cli.json # 🏠 NestJS CLI配置
├── 📄 docker-compose.yml # 🐳 Docker编排配置
├── 📄 Dockerfile # 🐳 Docker镜像配置
└── 📄 ecosystem.config.js # 🚀 PM2进程管理配置
🏗️ 分层架构设计
📊 架构分层说明
┌─────────────────────────────────────────────────────────────┐
│ 🌐 表现层 (Presentation) │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Controllers │ │ WebSocket │ │ Swagger UI │ │
│ │ (HTTP接口) │ │ Gateways │ │ (API文档) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────┐
│ 🎯 业务层 (Business) │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Auth Module │ │ UserMgmt │ │ Admin Module │ │
│ │ (用户认证) │ │ Module │ │ (管理员) │ │
│ │ │ │ (用户管理) │ │ │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Security Module │ │ Zulip Module │ │ Shared Module │ │
│ │ (安全防护) │ │ (Zulip集成) │ │ (共享组件) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────┐
│ ⚙️ 服务层 (Service) │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Login Core │ │ Admin Core │ │ Zulip Core │ │
│ │ (登录核心) │ │ (管理员核心) │ │ (Zulip核心) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Email Service │ │ Verification │ │ Logger Service │ │
│ │ (邮件服务) │ │ Service │ │ (日志服务) │ │
│ │ │ │ (验证码服务) │ │ │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
⬇️
┌─────────────────────────────────────────────────────────────┐
│ 🗄️ 数据层 (Data) │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Users Service │ │ Redis Service │ │ File Storage │ │
│ │ (用户数据) │ │ (缓存服务) │ │ (文件存储) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ MySQL/Memory │ │ Redis/File │ │ Logs/Data │ │
│ │ (数据库) │ │ (缓存实现) │ │ (日志数据) │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
🔄 数据流向
用户注册流程示例
1. 📱 用户请求 → AuthController.register()
2. 🔍 参数验证 → class-validator装饰器
3. 🎯 业务逻辑 → AuthService.register()
4. ⚙️ 核心服务 → LoginCoreService.createUser()
5. 📧 发送邮件 → EmailService.sendVerificationCode()
6. 🔢 生成验证码 → VerificationService.generate()
7. 💾 存储数据 → UsersService.create() + RedisService.set()
8. 📝 记录日志 → LoggerService.log()
9. ✅ 返回响应 → 用户收到成功响应
管理员操作流程示例
1. 🛡️ 管理员请求 → AdminController.resetUserPassword()
2. 🔐 权限验证 → AdminGuard.canActivate()
3. 🎯 业务逻辑 → AdminService.resetPassword()
4. ⚙️ 核心服务 → AdminCoreService.resetUserPassword()
5. 🔑 密码加密 → bcrypt.hash()
6. 💾 更新数据 → UsersService.update()
7. 📧 通知用户 → EmailService.sendPasswordReset()
8. 📝 审计日志 → LoggerService.audit()
9. ✅ 返回响应 → 管理员收到操作结果
🔄 双模式架构
🎯 设计目标
- 开发测试: 零依赖快速启动,无需安装MySQL、Redis等外部服务
- 生产部署: 高性能、高可用,支持集群和负载均衡
📊 模式对比
| 功能模块 | 🧪 开发测试模式 | 🚀 生产部署模式 |
|---|---|---|
| 数据库 | 内存存储 (UsersMemoryService) | MySQL (UsersService + TypeORM) |
| 缓存 | 文件存储 (FileRedisService) | Redis (RedisService + IORedis) |
| 邮件 | 控制台输出 (测试模式) | SMTP服务器 (生产模式) |
| 日志 | 控制台 + 文件 | 结构化日志 + 日志轮转 |
| 配置 | .env 默认配置 |
环境变量 + 配置中心 |
⚙️ 模式切换配置
开发测试模式 (.env)
# 数据存储模式
USE_FILE_REDIS=true # 使用文件存储代替Redis
NODE_ENV=development # 开发环境
# 数据库配置(注释掉,使用内存数据库)
# DB_HOST=localhost
# DB_USERNAME=root
# DB_PASSWORD=password
# 邮件配置(注释掉,使用测试模式)
# EMAIL_HOST=smtp.gmail.com
# EMAIL_USER=your_email@gmail.com
# EMAIL_PASS=your_password
生产部署模式 (.env.production)
# 数据存储模式
USE_FILE_REDIS=false # 使用真实Redis
NODE_ENV=production # 生产环境
# 数据库配置
DB_HOST=your_mysql_host
DB_PORT=3306
DB_USERNAME=your_username
DB_PASSWORD=your_password
DB_DATABASE=whale_town
# Redis配置
REDIS_HOST=your_redis_host
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
# 邮件配置
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_app_password
🔧 实现机制
依赖注入切换
// redis.module.ts
@Module({
providers: [
{
provide: 'IRedisService',
useFactory: (configService: ConfigService) => {
const useFileRedis = configService.get<boolean>('USE_FILE_REDIS');
return useFileRedis
? new FileRedisService()
: new RedisService(configService);
},
inject: [ConfigService],
},
],
})
export class RedisModule {}
配置驱动服务选择
// users.module.ts
@Module({
providers: [
{
provide: 'IUsersService',
useFactory: (configService: ConfigService) => {
const dbHost = configService.get<string>('DB_HOST');
return dbHost
? new UsersService()
: new UsersMemoryService();
},
inject: [ConfigService],
},
],
})
export class UsersModule {}
📦 模块依赖关系
🏗️ 模块依赖图
AppModule (应用主模块)
├── 📊 ConfigModule (全局配置)
├── 📝 LoggerModule (日志系统)
├── 🔴 RedisModule (缓存服务)
│ ├── RedisService (真实Redis)
│ └── FileRedisService (文件存储)
├── 🗄️ UsersModule (用户数据)
│ ├── UsersService (MySQL数据库)
│ └── UsersMemoryService (内存数据库)
├── 📧 EmailModule (邮件服务)
├── 🔢 VerificationModule (验证码服务)
├── 🔑 LoginCoreModule (登录核心)
├── 👑 AdminCoreModule (管理员核心)
├── 💬 ZulipCoreModule (Zulip核心)
│
├── 🎯 业务功能模块
│ ├── 🔐 AuthModule (用户认证)
│ │ └── 依赖: LoginCoreModule, EmailModule, VerificationModule
│ ├── 👥 UserMgmtModule (用户管理)
│ │ └── 依赖: UsersModule, LoggerModule
│ ├── 🛡️ AdminModule (管理员)
│ │ └── 依赖: AdminCoreModule, UsersModule
│ ├── 🔒 SecurityModule (安全防护)
│ │ └── 依赖: RedisModule, LoggerModule
│ ├── 💬 ZulipModule (Zulip集成)
│ │ └── 依赖: ZulipCoreModule, RedisModule
│ └── 🔗 SharedModule (共享组件)
🔄 模块交互流程
用户认证流程
AuthController → AuthService → LoginCoreService
↓
EmailService ← VerificationService ← RedisService
↓
UsersService
管理员操作流程
AdminController → AdminService → AdminCoreService
↓
LoggerService ← UsersService ← RedisService
安全防护流程
SecurityGuard → RedisService (频率限制)
→ LoggerService (审计日志)
→ ConfigService (维护模式)
🚀 扩展指南
📝 添加新的业务模块
1. 创建业务模块结构
# 创建模块目录
mkdir -p src/business/game/{dto,enums,guards,interfaces}
# 生成NestJS模块文件
nest g module business/game
nest g controller business/game
nest g service business/game
2. 实现业务逻辑
// src/business/game/game.module.ts
@Module({
imports: [
GameCoreModule, # 依赖核心服务
UsersModule, # 依赖用户数据
RedisModule, # 依赖缓存服务
],
controllers: [GameController],
providers: [GameService],
exports: [GameService],
})
export class GameModule {}
3. 创建对应的核心服务
# 创建核心服务
mkdir -p src/core/game_core
nest g module core/game_core
nest g service core/game_core
4. 更新主模块
// src/app.module.ts
@Module({
imports: [
// ... 其他模块
GameModule, # 添加新的业务模块
],
})
export class AppModule {}
🛠️ 添加新的工具服务
1. 创建工具服务
mkdir -p src/core/utils/notification
nest g module core/utils/notification
nest g service core/utils/notification
2. 定义服务接口
// src/core/utils/notification/notification.interface.ts
export interface INotificationService {
sendPush(userId: string, message: string): Promise<void>;
sendSMS(phone: string, message: string): Promise<void>;
}
3. 实现服务
// src/core/utils/notification/notification.service.ts
@Injectable()
export class NotificationService implements INotificationService {
async sendPush(userId: string, message: string): Promise<void> {
// 实现推送通知逻辑
}
async sendSMS(phone: string, message: string): Promise<void> {
// 实现短信发送逻辑
}
}
4. 配置依赖注入
// src/core/utils/notification/notification.module.ts
@Module({
providers: [
{
provide: 'INotificationService',
useClass: NotificationService,
},
],
exports: ['INotificationService'],
})
export class NotificationModule {}
🔌 添加新的API接口
1. 定义DTO
// src/business/game/dto/create-game.dto.ts
export class CreateGameDto {
@IsString()
@IsNotEmpty()
name: string;
@IsString()
@IsOptional()
description?: string;
}
2. 实现Controller
// src/business/game/game.controller.ts
@Controller('game')
@ApiTags('游戏管理')
export class GameController {
constructor(private readonly gameService: GameService) {}
@Post()
@ApiOperation({ summary: '创建游戏' })
async createGame(@Body() createGameDto: CreateGameDto) {
return this.gameService.create(createGameDto);
}
}
3. 实现Service
// src/business/game/game.service.ts
@Injectable()
export class GameService {
constructor(
@Inject('IGameCoreService')
private readonly gameCoreService: IGameCoreService,
) {}
async create(createGameDto: CreateGameDto) {
return this.gameCoreService.createGame(createGameDto);
}
}
4. 添加测试用例
// src/business/game/game.service.spec.ts
describe('GameService', () => {
let service: GameService;
let gameCoreService: jest.Mocked<IGameCoreService>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
GameService,
{
provide: 'IGameCoreService',
useValue: {
createGame: jest.fn(),
},
},
],
}).compile();
service = module.get<GameService>(GameService);
gameCoreService = module.get('IGameCoreService');
});
it('should create game', async () => {
const createGameDto = { name: 'Test Game' };
const expectedResult = { id: 1, ...createGameDto };
gameCoreService.createGame.mockResolvedValue(expectedResult);
const result = await service.create(createGameDto);
expect(result).toEqual(expectedResult);
expect(gameCoreService.createGame).toHaveBeenCalledWith(createGameDto);
});
});
📊 性能优化建议
1. 缓存策略
- Redis缓存: 用户会话、验证码、频繁查询数据
- 内存缓存: 配置信息、静态数据
- CDN缓存: 静态资源文件
2. 数据库优化
- 连接池: 复用数据库连接,减少连接开销
- 索引优化: 为查询字段建立合适的索引
- 查询优化: 避免N+1查询,使用JOIN优化关联查询
3. 日志优化
- 异步日志: 使用Pino的异步写入功能
- 日志分级: 生产环境只记录ERROR和WARN级别
- 日志轮转: 自动清理过期日志文件
🔒 安全加固建议
1. 数据验证
- 输入验证: 使用class-validator进行严格验证
- 类型检查: TypeScript静态类型检查
- SQL注入防护: TypeORM参数化查询
2. 认证授权
- 密码安全: bcrypt加密,强密码策略
- 会话管理: JWT + Redis会话存储
- 权限控制: 基于角色的访问控制(RBAC)
3. 通信安全
- HTTPS: 生产环境强制HTTPS
- CORS: 严格的跨域请求控制
- Rate Limiting: API请求频率限制
🏗️ 通过清晰的架构设计,Whale Town 实现了高内聚、低耦合的模块化架构,支持快速开发和灵活部署!