You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

1. 依赖与配置

  • 1.1 添加 redispymysql 依赖到 requirements.txt
  • 1.2 在 app/config.py 中新增 Redis 和 MySQL 连接配置项host、port、user、password、database
  • 1.3 在 docker-compose.yml 中新增 Redis 和 MySQL 服务定义

2. 数据库模型与初始化

  • 2.1 创建 app/mysql_database.py,实现 MySQL 连接引擎和 SessionLocal
  • 2.2 创建 app/redis_client.py,实现 Redis 连接池和客户端封装
  • 2.3 在 app/main.pylifespan 中初始化 Redis 和 MySQL 连接,检测可用性
  • 2.4 创建 MySQL 表结构初始化脚本(复用现有 ORM 模型)

3. 数据迁移

  • 3.1 创建数据迁移脚本,从 SQLite 读取历史数据并写入 MySQL
  • 3.2 在应用启动时检测 MySQL 表是否为空,自动触发迁移

4. 存储管理层

  • 4.1 创建 app/storage_manager.py,实现 StorageManager 抽象层
  • 4.2 实现 Redis 缓存读取逻辑(命中返回,未命中回源 MySQL 并回填)
  • 4.3 实现 MySQL 持久化读写逻辑
  • 4.4 实现三级降级策略Redis → MySQL → SQLite
  • 4.5 实现降级状态检测和恢复机制

5. 双写与缓存一致性

  • 5.1 实现刷新接口双写逻辑:先删 Redis 缓存,再写 MySQL最后更新 Redis
  • 5.2 实现双写顺序保证和错误处理MySQL 失败回滚Redis 失败记录日志)
  • 5.3 实现缓存未命中回填逻辑TTL 30 天)

6. 接口改造

  • 6.1 改造 app/services/cache.py 中的行情数据读取接口,使用 StorageManager
  • 6.2 改造 app/services/cache.py 中的刷新接口,使用双写逻辑
  • 6.3 改造 app/services/cache.py,使用 StorageManager 写入数据API 层零改动)

7. 测试与验证

  • 7.1 验证 Redis 缓存命中场景
  • 7.2 验证 Redis 缓存未命中回源 MySQL 场景
  • 7.3 验证 Redis 不可用降级到 MySQL 场景
  • 7.4 验证 Redis 和 MySQL 均不可用降级到 SQLite 场景
  • 7.5 验证刷新接口双写一致性
  • 7.6 验证数据迁移完整性