cosmo/REDIS.md

40 lines
2.4 KiB
Markdown
Raw Permalink Blame History

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.

# Redis 键结构概览
## Redis 中主要存在以下几类键Key Prefix
* user:tokens:* (对应您提到的 token 和 user 相关的)
* positions:* (对应 positions)
* cosmo:danmaku:stream (留言板)
## Positions (位置数据) 的机制
在 backend/app/services/db_service.py 和 redis_cache.py 中体现了位置数据的缓存策略。
`positions:{start_time}:{end_time}:{step}` (String/JSON 类型)
* 目的:缓存前端请求的“天体位置列表”数据。
* 机制 (多级缓存 L1/L2/L3)
1. 请求到来:当 API 收到 /celestial/positions 请求时,它会根据查询参数(开始时间、结束时间、步长)生成一个唯一的 Cache Key。
2. L2 (Redis):首先检查 Redis 中是否有这个 Key。
* 命中:直接返回 Redis 中的 JSON 数据。这是最快的,通常在毫秒级。
* 未命中:继续向下查询。
3. L3 (Database/Horizons):如果 Redis 没有,系统会去 PostgreSQL 数据库查询(预取的数据),或者调用 NASA Horizons API 获取实时数据。
4. 回写:获取到数据后,系统会将结果序列化为 JSON写入 Redis并设置过期时间TTL例如 1 小时或 7 天)。
* 特点:
* 查询驱动:只有被请求过的数据才会被缓存。
* 预热 (Preheat):系统有 preheat 机制,会在启动时自动计算未来一段时间(如 30 天)的位置数据并写入 Redis确保用户访问时是秒开的。
## Cosmo / danmaku (留言板)
* `cosmo:danmaku:stream` (Sorted Set 类型):
* 这是我们刚刚实现的留言板/弹幕功能。
* 使用 Sorted Set以时间戳Timestamp作为 Score。
* 这允许我们高效地执行“获取最近 5 分钟的消息” (ZRANGEBYSCORE) 和“清理 24 小时前的消息” (ZREMRANGEBYSCORE) 操作。
## 总结架构图
| 键前缀 (Key Prefix) | 类型 (Type) | 用途 (Purpose) | 有效期 (TTL) |
|------|--------------|-------------|------|
| user:tokens:{uid} | Set | 存该用户所有活动的 JWT Token用于多端登录和注销。 | 随 Token 过期 |
| positions:{args} | String (JSON) | API 响应缓存。存前端需要的天体坐标数组。 | 1小时 (实时) / 7天 (历史) |
| cosmo:danmaku:stream | ZSet | 留言板消息流。按时间排序,自动过期。 | 24 小时 (可配) |