32 KiB
32 KiB
系统架构设计文档
本文档详细说明QY LTY Backend的整体架构设计、技术选型和关键组件。
1. 架构概览
1.1 系统架构图
┌─────────────────────────────────────────┐
│ 客户端层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Web App │ │ Mobile │ │ Device │ │
│ │ │ │ App │ │ SDK │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────┬───────────────────────────┘
│ HTTP/HTTPS + WebSocket
┌─────────────┴───────────────────────────┐
│ 网关/负载均衡 │
│ ┌─────────────────────┐ │
│ │ Nginx │ │
│ └─────────────────────┘ │
└─────────────┬───────────────────────────┘
│
┌─────────────┴───────────────────────────┐
│ 应用服务层 │
│ ┌─────────────────────────────────────┐ │
│ │ Django Application │ │
│ │ ┌─────────┐ ┌─────────────────┐ │ │
│ │ │ ASGI │ │ Django │ │ │
│ │ │ Server │ │ HTTP Views │ │ │
│ │ │(Daphne) │ │ │ │ │
│ │ └─────────┘ └─────────────────┘ │ │
│ │ ┌─────────┐ ┌─────────────────┐ │ │
│ │ │WebSocket│ │ DRF │ │ │
│ │ │Consumers│ │ API Views │ │ │
│ │ └─────────┘ └─────────────────┘ │ │
│ └─────────────────────────────────────┘ │
└─────────────┬───────────────────────────┘
│
┌─────────────┴───────────────────────────┐
│ 业务逻辑层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │
│ │ UserApp │ │ AIApp │ │ Card │ │
│ └─────────┘ └─────────┘ └─────────────┘ │
│ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │
│ │ Device │ │Achievement│ │ Subscription│ │
│ └─────────┘ └─────────┘ └─────────────┘ │
└─────────────┬───────────────────────────┘
│
┌─────────────┴───────────────────────────┐
│ 数据存储层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │
│ │PostgreSQL│ │ Redis │ │ File Storage│ │
│ │ │ │ Cache │ │ (OSS) │ │
│ └─────────┘ └─────────┘ └─────────────┘ │
└─────────────┬───────────────────────────┘
│
┌─────────────┴───────────────────────────┐
│ 第三方服务层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │
│ │ AI服务 │ │音频服务 │ │ 云服务 │ │
│ │ (Kimi) │ │(多厂商) │ │ (阿里云等) │ │
│ └─────────┘ └─────────┘ └─────────────┘ │
└─────────────────────────────────────────┘
1.2 技术栈总览
| 层级 | 技术组件 | 作用 |
|---|---|---|
| Web框架 | Django 4.2.13 | 核心Web框架 |
| API框架 | Django REST Framework | RESTful API开发 |
| 实时通信 | Django Channels | WebSocket支持 |
| ASGI服务器 | Daphne | 异步Web服务器 |
| 数据库 | PostgreSQL | 主数据库 |
| 缓存 | Redis | 缓存和消息队列 |
| 任务调度 | APScheduler | 定时任务管理 |
| API文档 | drf-yasg | OpenAPI文档生成 |
2. 核心模块架构
2.1 用户管理系统 (UserApp)
UserApp Architecture:
┌─────────────────────────────────────────────┐
│ UserApp │
│ ┌─────────────────────────────────────────┐ │
│ │ Models │ │
│ │ ┌─────────────────────────────────────┐ │ │
│ │ │ ParadiseUser │ │ │
│ │ │ - Custom User Model │ │ │
│ │ │ - Phone, Email, Profile Fields │ │ │
│ │ │ - MBTI, Interests, etc. │ │ │
│ │ └─────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Views │ │
│ │ ┌─────────────┐ ┌──────────────────┐ │ │
│ │ │ Auth Views │ │ Management Views │ │ │
│ │ │ - Login │ │ - Profile CRUD │ │ │
│ │ │ - Register │ │ - User Search │ │ │
│ │ │ - SMS │ │ - Admin Panel │ │ │
│ │ └─────────────┘ └──────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Authentication │ │
│ │ - Token Authentication │ │
│ │ - Session Authentication │ │
│ │ - Social Authentication (WeChat) │ │
│ │ - SMS Verification (Aliyun) │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
核心功能:
- 自定义用户模型支持多种认证方式
- 手机短信验证集成阿里云SMS
- 社交登录集成微信等平台
- 用户配置文件管理(MBTI、兴趣等)
2.2 AI对话系统 (AIApp)
AIApp Architecture:
┌─────────────────────────────────────────────┐
│ AIApp │
│ ┌─────────────────────────────────────────┐ │
│ │ Chat Engine │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │Single Chat │ │ Multi Chat │ │ │
│ │ │- Bot Based │ │ - Session Based │ │ │
│ │ │- Stateless │ │ - Context Aware │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Audio Processing │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ ASR │ │ TTS │ │ │
│ │ │(Speech2Text)│ │ (Text2Speech) │ │ │
│ │ │- Aliyun NLS │ │ - Volcengine │ │ │
│ │ │- Multi Lang │ │ - Aliyun │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ AI Providers │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Kimi │ │ OpenAI Compatible │ │ │
│ │ │(Moonshot AI)│ │ Models │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
核心功能:
- 支持单轮和多轮对话
- 语音输入输出完整支持
- 多AI服务提供商适配
- 上下文管理和会话持久化
2.3 卡片管理系统 (Card)
Card System Architecture:
┌─────────────────────────────────────────────┐
│ Card System │
│ ┌─────────────────────────────────────────┐ │
│ │ Data Models │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │CardTemplate │ │ CardBatch │ │ │
│ │ │- Category │ │ - Bulk Generate │ │ │
│ │ │- Attributes │ │ - QR Code │ │ │
│ │ │- Rarity │ │ - Expiry │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Card │ │ UsageLog │ │ │
│ │ │- Unique Code│ │ - Audit Trail │ │ │
│ │ │- QR Image │ │ - Analytics │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Card Categories │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Dance │ │ Song │ │ │
│ │ │- Style │ │ - Genre, BPM │ │ │
│ │ │- Difficulty │ │ - Audio File │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Clothing │ │ Game │ │ │
│ │ │- Style │ │ - Type, Level │ │ │
│ │ │- Season │ │ - Rewards │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
核心功能:
- 模板化卡片生成系统
- 批次管理和二维码生成
- 分类属性系统(舞蹈、音乐、服装、游戏)
- 使用跟踪和分析
2.4 设备交互系统 (Device Interaction)
Device Interaction Architecture:
┌─────────────────────────────────────────────┐
│ Device Interaction │
│ ┌─────────────────────────────────────────┐ │
│ │ WebSocket Layer │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Consumer │ │ Authentication │ │ │
│ │ │- Message │ │ - Token Based │ │ │
│ │ │- Routing │ │ - User Based │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Device Management │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │Device Types │ │ Device Batch │ │ │
│ │ │- Categories │ │ - Production Info │ │ │
│ │ │- Properties │ │ - Serial Numbers │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Devices │ │ User Bindings │ │ │
│ │ │- MAC Address│ │ - Device-User Link │ │ │
│ │ │- Activation │ │ - Primary Device │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Message System │ │
│ │ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │Message Types│ │ Integrations │ │ │
│ │ │- Chat │ │ - Weather API │ │ │
│ │ │- Weather │ │ - Music Service │ │ │
│ │ │- Control │ │ - Dance Library │ │ │
│ │ └─────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
核心功能:
- 基于Django Channels的WebSocket通信
- 设备生命周期管理
- 用户设备绑定系统
- 实时消息分发
3. 数据架构设计
3.1 数据库设计原则
数据库选择:PostgreSQL
- 原因:支持JSON字段、全文搜索、扩展性好
- 版本:PostgreSQL 12+
- 字符集:UTF-8
- 时区:Asia/Shanghai
3.2 核心数据模型关系
-- 用户系统
ParadiseUser ||--o{ UserDevice : binds
ParadiseUser ||--o{ UserAchievement : earns
ParadiseUser ||--o{ CardUsageLog : uses
-- 卡片系统
CardTemplate ||--o{ CardBatch : generates
CardBatch ||--o{ Card : contains
Card ||--o{ CardUsageLog : tracks
-- 设备系统
DeviceType ||--o{ DeviceBatch : groups
DeviceBatch ||--o{ Device : contains
Device ||--o{ UserDevice : binds
-- 成就系统
Achievement ||--o{ UserAchievement : awards
3.3 数据分区策略
-- 时间分区示例(日志表)
CREATE TABLE card_usage_logs (
id BIGSERIAL,
card_id INTEGER,
user_id INTEGER,
used_at TIMESTAMP,
-- 其他字段
) PARTITION BY RANGE (used_at);
-- 月份分区
CREATE TABLE card_usage_logs_2023_01 PARTITION OF card_usage_logs
FOR VALUES FROM ('2023-01-01') TO ('2023-02-01');
4. 缓存架构
4.1 Redis 缓存策略
# 缓存层级设计
CACHE_LEVELS = {
'L1': { # 应用级缓存
'timeout': 300, # 5分钟
'keys': [
'user_profile:{user_id}',
'card_template:{template_id}',
'achievement_list'
]
},
'L2': { # 会话级缓存
'timeout': 1800, # 30分钟
'keys': [
'chat_session:{session_id}',
'device_status:{device_id}'
]
},
'L3': { # 长期缓存
'timeout': 86400, # 24小时
'keys': [
'card_batch_stats:{batch_id}',
'user_achievement_stats:{user_id}'
]
}
}
4.2 Channel Layers配置
# WebSocket消息通道配置
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
"capacity": 1500, # 每个通道最大消息数
"expiry": 60, # 消息过期时间(秒)
},
},
}
5. API设计架构
5.1 RESTful API设计原则
API 设计规范:
┌─────────────────────────────────────────────┐
│ API Layer │
│ ┌─────────────────────────────────────────┐ │
│ │ URL Structure │ │
│ │ /api/{version}/{module}/{resource}/ │ │
│ │ 例如: /api/v1/user/auth/login/ │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ HTTP Methods │ │
│ │ GET - 查询资源 │ │
│ │ POST - 创建资源 │ │
│ │ PUT - 更新资源(完整) │ │
│ │ PATCH - 更新资源(部分) │ │
│ │ DELETE - 删除资源 │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Response Format │ │
│ │ { │ │
│ │ "status": "success/error", │ │
│ │ "code": 200, │ │
│ │ "data": {...}, │ │
│ │ "message": "操作成功" │ │
│ │ } │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
5.2 认证和授权架构
# 认证流程
AUTHENTICATION_FLOW = {
'Token': {
'header': 'Authorization: Bearer {token}',
'use_case': 'API客户端',
'expiry': '永久(直到撤销)'
},
'Session': {
'header': 'Cookie: sessionid={id}',
'use_case': 'Web浏览器',
'expiry': '2周'
},
'WebSocket': {
'query_param': '?token={token}',
'use_case': 'WebSocket连接',
'validation': 'Token或用户ID'
}
}
6. 第三方服务集成架构
6.1 AI服务适配层
# AI服务抽象层
class AIServiceInterface:
def single_chat(self, message: str, bot_id: int) -> Response:
pass
def multi_chat(self, message: str, session_id: str) -> Response:
pass
# 具体实现
class KimiAIService(AIServiceInterface):
def __init__(self, api_key, base_url):
self.client = OpenAI(api_key=api_key, base_url=base_url)
def single_chat(self, message, bot_id):
# Kimi API调用实现
pass
6.2 音频服务适配层
# 音频服务工厂模式
class AudioServiceFactory:
@staticmethod
def get_service(provider: str) -> BaseAudioService:
services = {
'aliyun': AliyunAudioService,
'huoshan': HuoshanAudioService,
'tencent': TencentAudioService
}
return services[provider]()
# 统一音频服务接口
class BaseAudioService:
def text_to_speech(self, text: str) -> AudioFile:
pass
def speech_to_text(self, audio: bytes) -> str:
pass
6.3 云服务集成
# 阿里云服务集成
ALIYUN_SERVICES = {
'SMS': {
'service': 'dysmsapi',
'use_case': '短信验证码发送'
},
'OSS': {
'service': 'oss2',
'use_case': '文件存储'
},
'NLS': {
'service': 'nls',
'use_case': '语音识别'
},
'VI': {
'service': 'facebody',
'use_case': '图像识别'
}
}
7. 消息队列和异步处理
7.1 任务队列架构
# 使用APScheduler进行任务调度
from apscheduler.schedulers.django import DjangoScheduler
scheduler = DjangoScheduler()
# 定时任务示例
@scheduler.scheduled_job('cron', hour=0, minute=0)
def cleanup_expired_cards():
"""清理过期卡片"""
pass
@scheduler.scheduled_job('cron', hour=2, minute=0)
def update_achievement_stats():
"""更新成就统计"""
pass
7.2 异步任务设计
# 异步任务装饰器
import asyncio
from functools import wraps
def async_task(func):
@wraps(func)
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
return loop.run_in_executor(None, func, *args, **kwargs)
return wrapper
@async_task
def process_audio_file(audio_file):
"""异步处理音频文件"""
# 耗时的音频处理操作
pass
8. 安全架构
8.1 安全策略
SECURITY_MEASURES = {
'Authentication': {
'token_expiry': '不过期(需要主动撤销)',
'session_expiry': '2周',
'password_policy': '最少8位,包含数字和字母'
},
'Authorization': {
'role_based': 'Django用户组和权限系统',
'resource_based': 'DRF权限类',
'device_binding': '设备MAC地址绑定'
},
'Data_Protection': {
'encryption': 'Django内置密码加密',
'sensitive_data': 'PII数据不记录在日志中',
'api_rate_limit': 'DRF限流机制'
}
}
8.2 CORS和CSRF配置
# CORS配置
CORS_ALLOW_ALL_ORIGINS = True # 开发环境
CORS_ALLOWED_ORIGINS = [ # 生产环境
"https://yourdomain.com",
"https://www.yourdomain.com",
]
# CSRF保护(API禁用,Web界面启用)
CSRF_EXEMPT_URLS = [
r'^api/', # API接口豁免CSRF
]
9. 监控和日志架构
9.1 日志系统设计
# 分层日志配置
LOGGING_ARCHITECTURE = {
'Application_Logs': {
'level': 'INFO',
'handler': 'AliyunLogHandler',
'format': 'structured_json',
'retention': '30天'
},
'Access_Logs': {
'level': 'INFO',
'handler': 'FileHandler',
'format': 'nginx_format',
'rotation': '每日'
},
'Error_Logs': {
'level': 'ERROR',
'handler': 'AliyunLogHandler + EmailHandler',
'format': 'detailed_traceback',
'alert': True
}
}
9.2 性能监控
# 数据库连接监控
def print_database_and_cache_info():
"""启动时打印数据库和缓存连接信息"""
# 测试数据库连接延迟
# 测试缓存连接延迟
# 记录连接状态到日志
pass
10. 扩展性设计
10.1 水平扩展策略
扩展架构:
┌─────────────────────────────────────────────┐
│ Load Balancer │
│ (Nginx) │
└─────────────┬───────────────────────────────┘
│
┌─────────┴─────────┬─────────────────────┐
│ │ │
┌───▼────┐ ┌───▼────┐ ┌───▼────┐
│App │ │App │ │App │
│Server 1│ │Server 2│ ... │Server N│
└────────┘ └────────┘ └────────┘
│ │ │
└─────────┬─────────┴─────────────────────┘
│
┌─────────▼─────────┐
│ │
┌───▼────┐ ┌───▼────┐
│Database│ │ Redis │
│Cluster │ │Cluster │
└────────┘ └────────┘
10.2 模块化插件架构
# 插件系统设计
class PluginBase:
def __init__(self, config):
self.config = config
def initialize(self):
pass
def process(self, data):
pass
# 音频服务插件
class AudioPlugin(PluginBase):
def process(self, audio_data):
# 音频处理逻辑
pass
# 插件管理器
class PluginManager:
def __init__(self):
self.plugins = {}
def register_plugin(self, name, plugin_class):
self.plugins[name] = plugin_class
def get_plugin(self, name):
return self.plugins.get(name)
11. 部署架构
11.1 容器化部署
# 多阶段构建
FROM python:3.9-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.9-slim
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages
COPY . .
CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "qy_lty.asgi:application"]
11.2 云原生部署
# Kubernetes部署示例
apiVersion: apps/v1
kind: Deployment
metadata:
name: qy-lty-backend
spec:
replicas: 3
selector:
matchLabels:
app: qy-lty-backend
template:
metadata:
labels:
app: qy-lty-backend
spec:
containers:
- name: backend
image: qy-lty-backend:latest
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
这个架构文档涵盖了系统的各个方面,为开发者提供了全面的技术架构理解。每个组件都经过精心设计,支持高可用、可扩展和可维护的系统架构。