基于TTL的内存缓存实现:macOS活动追踪工具缓存方案咨询
本地优先macOS生产力追踪工具的缓存方案反馈请求
背景
我正在构建一款本地优先的macOS生产力追踪工具,通过读取系统KnowledgeC数据库分析专注时间与上下文切换。由于对该SQLite数据库进行聚合查询开销较高,我实现了一个带TTL的简单内存缓存。
该应用提供展示日/周指标的Web仪表盘,用户可能频繁刷新,数据无需实时(1-2分钟的延迟是可接受的)。
内存缓存实现
"""Simple in-memory cache with TTL.""" import time from dataclasses import dataclass from typing import Any @dataclass class CacheEntry: """Cache entry with expiration.""" value: Any expires_at: float class InMemoryCache: """Simple in-memory cache with TTL expiration.""" def __init__(self, ttl_seconds: int = 60) -> None: self.ttl_seconds = ttl_seconds self._cache: dict[str, CacheEntry] = {} def get(self, key: str) -> Any | None: """Get value from cache if not expired.""" entry = self._cache.get(key) if entry is None: return None if time.time() > entry.expires_at: del self._cache[key] return None return entry.value def set(self, key: str, value: Any) -> None: """Set value in cache with TTL.""" expires_at = time.time() + self.ttl_seconds self._cache[key] = CacheEntry(value=value, expires_at=expires_at) def clear(self) -> None: """Clear all cache entries.""" self._cache.clear()
具体疑问
- 使用字典手动检查TTL是否过于简单?是否应该使用
cachetools或类似库? - 是否应该添加文件级的L2缓存?
- 线程安全问题:FastAPI应用是异步的,但缓存操作未加锁,该如何处理?
- 内存管理问题:当前缓存无最大大小限制,仅基于TTL进行驱逐,是否需要优化?
当前表现
- 缓存命中可将查询时间从约50ms降至<1ms
- 60秒的TTL非常符合我的使用场景
- 仅进行日/周查询时未出现内存问题
内容的提问来源于stack exchange,提问作者Rustem K
相关产品推荐
相关产品推荐

