auto_trade_sys/docs/缓存优化_写入Valkey.md
薇薇安 59e25558cd feat(redis_cache, kline_stream, user_data_stream, risk_manager): 优化缓存机制与内存管理
在多个模块中引入 Redis 作为主要缓存机制,减少进程内存占用。更新 `binance_client.py`、`kline_stream.py`、`user_data_stream.py` 和 `risk_manager.py`,实现优先从 Redis 读取数据,降级到内存缓存。调整缓存 TTL 和最大条数,确保系统稳定性与性能。此改动提升了数据访问效率,优化了内存使用,增强了系统的整体性能。
2026-02-19 00:19:54 +08:00

72 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 缓存策略:全用 Redis基本不占服务器内存
## 目标
- **全量缓存以 Redis/Valkey 为主**:有 Redis 时只读只写 Redis进程内基本不保留缓存减轻服务器内存压力。
- **Redis 内容全部带过期时间**:所有写入 Redis 的键均设置 TTL不在 Redis 内无限增长。
## 一、Redis 键与 TTL 统一配置
所有 TTL 与键前缀集中在 `trading_system/redis_ttl.py` 中定义,**禁止**在 Redis 中写入无过期时间的业务键。
| 用途 | 键/前缀示例 | TTL | 说明 |
|----------------|--------------------------|-----------|----------------|
| 持仓缓存 | `ats:positions:cache` | 300 | 5 分钟 |
| 余额缓存 | `ats:balance:cache:USDT` | 300 | 5 分钟 |
| K 线WS 写入)| `market:kline:{s}:{i}` | 600 | 10 分钟 |
| 24h 行情 | `ticker_24h:{symbol}` | 30 | 单 symbol |
| 全市场 24h | `market:ticker_24h` | 120 | 2 分钟 |
| BookTicker | `market:book_ticker` | 30 | 30 秒 |
| 交易对信息 | `symbol_info:{symbol}` | 3600 | 1 小时 |
| listenKey 缓存 | `listen_key:*` | 3300 | 55 分钟 |
| 市场 WS Leader | `market_ws_leader` | 30 | 选主续期 |
更多见 `trading_system/redis_ttl.py`(含 K 线按 interval 的 TTL 等)。
## 二、各模块行为
### 1. RedisCache 降级内存缓存
**文件**: `trading_system/redis_cache.py`
- Redis 不可用时降级到进程内存。
- 内存缓存**有上限**:最多 200 条;单条** 5 分钟**过期,过期或满时淘汰最久未用,避免无限增长。
### 2. K 线
**文件**: `trading_system/kline_stream.py`
- Leader 进程WebSocket 收到 K 线后写入 RedisTTL 见 `redis_ttl.TTL_KLINE_STREAM`**写入成功后从进程内 `_kline_cache` 删除该 key**,以 Redis 为准、基本不占服务器内存。
- 非 Leader / 读路径:从 Redis 读(`get_klines_from_redis`);进程内仅保留未刷写 Redis 的少量缓冲。
### 3. 持仓 / 余额
**文件**: `trading_system/user_data_stream.py`
- **有 Redis 时**:只写 Redis**不写** `_position_updates_cache` / `_balance_updates_cache`;读时优先从 Redis 读。
- **无 Redis 时**:写进程内存,读时从进程内存读。
- 所有 Redis 键带 TTL`redis_ttl.TTL_POSITIONS` / `TTL_BALANCE`)。
### 4. 价格与交易对信息
**文件**: `trading_system/binance_client.py`
- **价格get_ticker_24h**:先读 RedisREST 回源后只写 Redis仅当 Redis 写入失败时才写进程内存(降级)。
- **交易对信息get_symbol_info**:先读 Redis从 DB/API 得到后写 Redis仅当 Redis 不可用时才写入 `_symbol_info_cache`
### 5. 其他
- 行情 / BookTicker / listenKey / 推荐结果等:凡写入 Redis 的均带 TTL见各模块及 `redis_ttl.py`
## 三、使用与运维
1. **保证 Redis/Valkey 可用**:配置好 `REDIS_URL`(如 AWS Valkey确保交易服务能连上。
2. **重启生效**:改缓存逻辑后需重启交易服务。
3. **监控 Redis 内存**:在 Valkey 控制台或 `INFO memory` 查看内存;所有键有过期,不应无限增长。
4. **进程内存**:正常情况下进程内缓存很少;仅 Redis 不可用时才用内存降级(条数/过期受控)。
## 四、预期效果
- 服务器进程内存占用明显下降(有 Redis 时基本不存大块缓存)。
- Redis/Valkey 内所有业务键有过期,不会无限使用内存。