2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
缓存管理器 - 纯Key-Value缓存实现
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
提供简单高效的内存缓存接口,不包含业务逻辑
|
|
|
|
|
|
职责:只负责数据的存取,不涉及数据加载、验证、计算
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import logging
|
2025-12-23 17:56:01 +08:00
|
|
|
|
from typing import Dict, Optional, Any, Union
|
2025-12-19 06:27:22 +08:00
|
|
|
|
import pandas as pd
|
2025-12-21 02:23:53 +08:00
|
|
|
|
from src.core.config import Config
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CacheManager:
|
|
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
纯缓存管理器
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
职责:
|
|
|
|
|
|
- Key-Value存储:按symbol_period组织数据
|
|
|
|
|
|
- 元数据管理:自动维护数据时间范围
|
2025-12-19 07:13:01 +08:00
|
|
|
|
- 内存管理:支持内存限制和统计
|
2025-12-23 17:56:01 +08:00
|
|
|
|
- 缓存失效:支持精确和批量失效
|
|
|
|
|
|
|
|
|
|
|
|
不包含:
|
|
|
|
|
|
- ✗ 数据加载逻辑(由DataService负责)
|
|
|
|
|
|
- ✗ 数据验证逻辑(由DataService负责)
|
|
|
|
|
|
- ✗ 指标计算逻辑(由DataService负责)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
2025-12-27 22:52:40 +08:00
|
|
|
|
def __init__(self, config: Union[dict, Config], db_manager=None):
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
初始化缓存管理器
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
2025-12-21 02:23:53 +08:00
|
|
|
|
config: 配置字典或Config对象,包含cache相关配置
|
2025-12-27 22:52:40 +08:00
|
|
|
|
db_manager: 数据库管理器(可选),用于缓存未命中时从数据库加载
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
self.config = config
|
2025-12-27 22:52:40 +08:00
|
|
|
|
self._db_manager = db_manager
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
# 获取缓存配置
|
|
|
|
|
|
cache_config = config.get("cache", {})
|
|
|
|
|
|
self.enabled = cache_config.get("enabled", True)
|
2025-12-23 17:56:01 +08:00
|
|
|
|
self.max_memory_mb = cache_config.get("max_memory_mb", 4096) # 默认4GB
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
# 核心数据结构
|
|
|
|
|
|
self._cache: Dict[str, Dict[str, Any]] = {}
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(
|
2025-12-27 22:52:40 +08:00
|
|
|
|
f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB, "
|
|
|
|
|
|
f"db_fallback={'enabled' if db_manager else 'disabled'}"
|
2025-12-19 06:27:22 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]:
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
2025-12-27 22:52:40 +08:00
|
|
|
|
获取K线数据(带数据库降级)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
2025-12-23 17:56:01 +08:00
|
|
|
|
period: 周期
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
2025-12-27 22:52:40 +08:00
|
|
|
|
K线DataFrame或None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
|
2025-12-27 22:52:40 +08:00
|
|
|
|
# 1. 先查缓存
|
2025-12-19 06:27:22 +08:00
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
cached = self._cache[key]
|
2025-12-23 17:56:01 +08:00
|
|
|
|
cache_data = cached.get("klines")
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if cache_data is not None and not cache_data.empty:
|
|
|
|
|
|
return cache_data
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-27 22:52:40 +08:00
|
|
|
|
# 2. 缓存未命中,尝试从数据库加载
|
|
|
|
|
|
if self._db_manager:
|
|
|
|
|
|
logger.debug(f"Cache miss: {key}, loading from database")
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 从数据库加载所有数据
|
|
|
|
|
|
df = self._db_manager.load_klines_all(symbol, period)
|
|
|
|
|
|
|
|
|
|
|
|
if df is not None and not df.empty:
|
|
|
|
|
|
# 加载成功,填充缓存
|
|
|
|
|
|
self.set_klines(symbol, period, {"klines": df})
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"Loaded {len(df)} rows from database and cached: {key}"
|
|
|
|
|
|
)
|
|
|
|
|
|
return df
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"Failed to load from database: {key}, error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
# 3. 数据库也没有
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def set_klines(self, symbol: str, period: str, data: Dict[str, Any]) -> None:
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
设置缓存数据
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
2025-12-23 17:56:01 +08:00
|
|
|
|
data: 数据字典,必须包含'klines'键,可选包含指标数据
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
|
|
|
|
|
|
# 构造缓存项
|
|
|
|
|
|
if "meta" not in data:
|
|
|
|
|
|
# 自动添加元数据
|
|
|
|
|
|
klines = data.get("klines")
|
|
|
|
|
|
if klines is not None and not klines.empty:
|
|
|
|
|
|
time_range = (klines.index.min(), klines.index.max())
|
|
|
|
|
|
else:
|
|
|
|
|
|
time_range = (None, None)
|
|
|
|
|
|
|
|
|
|
|
|
data["meta"] = {
|
|
|
|
|
|
"time_range": time_range,
|
|
|
|
|
|
}
|
|
|
|
|
|
self._cache[key] = data
|
|
|
|
|
|
logger.debug(f"Cache set: {key}, time_range={data['meta']['time_range']}")
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def get_indicator(
|
|
|
|
|
|
self, symbol: str, period: str, indicator_type: str
|
|
|
|
|
|
) -> Optional[pd.DataFrame]:
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
获取指标数据(纯缓存查询)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
|
|
|
|
|
indicator_type: 指标类型(如IndicatorType.MACD)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
指标DataFrame或None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
return None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
key = self._make_key(symbol, period)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
cached = self._cache[key]
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if indicator_type in cached:
|
|
|
|
|
|
indicator_data = cached[indicator_type]
|
|
|
|
|
|
if indicator_data is not None and not indicator_data.empty:
|
|
|
|
|
|
return indicator_data
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def set_indicator(
|
2025-12-19 06:49:29 +08:00
|
|
|
|
self,
|
|
|
|
|
|
symbol: str,
|
|
|
|
|
|
period: str,
|
2025-12-23 17:56:01 +08:00
|
|
|
|
indicator_type: str,
|
|
|
|
|
|
indicator_data: pd.DataFrame,
|
|
|
|
|
|
) -> None:
|
2025-12-19 06:49:29 +08:00
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
设置指标数据
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
2025-12-23 17:56:01 +08:00
|
|
|
|
indicator_type: 指标类型(如IndicatorType.MACD)
|
|
|
|
|
|
indicator_data: 指标DataFrame
|
2025-12-19 06:49:29 +08:00
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
|
|
|
|
|
|
if key in self._cache:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 更新已有缓存项
|
|
|
|
|
|
self._cache[key][indicator_type] = indicator_data
|
|
|
|
|
|
logger.debug(f"Cache set indicator: {key}_{indicator_type}")
|
|
|
|
|
|
else:
|
2025-12-19 06:49:29 +08:00
|
|
|
|
logger.warning(
|
2025-12-23 17:56:01 +08:00
|
|
|
|
f"Cannot set indicator {indicator_type} for {key}: klines not cached. "
|
|
|
|
|
|
f"Please cache klines first using set()."
|
2025-12-19 06:49:29 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def clear_klines(self, symbol: str, period: str) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
清除指定标的和周期的K线缓存
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
return
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
key = self._make_key(symbol, period)
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
del self._cache[key]
|
|
|
|
|
|
logger.debug(f"Cache cleared: {key}")
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def clear_indicator(self, symbol: str, period: str, indicator_type: str) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
清除指定标的、周期和指标类型的缓存
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
|
|
|
|
|
indicator_type: 指标类型(如IndicatorType.MACD)
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
return
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
key = self._make_key(symbol, period)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
if key in self._cache and indicator_type in self._cache[key]:
|
|
|
|
|
|
del self._cache[key][indicator_type]
|
|
|
|
|
|
logger.debug(f"Cache cleared indicator: {key}_{indicator_type}")
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
def get_stats(self) -> Dict[str, Any]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取缓存统计信息
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
|
|
|
|
|
Returns:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
统计信息字典
|
2025-12-19 06:49:29 +08:00
|
|
|
|
"""
|
2025-12-23 17:56:01 +08:00
|
|
|
|
# 按标的统计
|
|
|
|
|
|
symbols_stats = {}
|
|
|
|
|
|
for key, cached in self._cache.items():
|
|
|
|
|
|
symbol = key.split("_")[0]
|
|
|
|
|
|
if symbol not in symbols_stats:
|
|
|
|
|
|
symbols_stats[symbol] = {
|
|
|
|
|
|
"periods": [],
|
|
|
|
|
|
}
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
period = "_".join(key.split("_")[1:])
|
|
|
|
|
|
symbols_stats[symbol]["periods"].append(period)
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return {
|
|
|
|
|
|
"enabled": self.enabled,
|
|
|
|
|
|
"size": len(self._cache),
|
|
|
|
|
|
"memory_mb": self._estimate_memory(),
|
|
|
|
|
|
"max_memory_mb": self.max_memory_mb,
|
|
|
|
|
|
"symbols": symbols_stats,
|
|
|
|
|
|
}
|
2025-12-19 06:49:29 +08:00
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
def _make_key(self, symbol: str, period: str) -> str:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
"""构造缓存键"""
|
2025-12-19 06:27:22 +08:00
|
|
|
|
return f"{symbol}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
def _estimate_memory(self) -> float:
|
2025-12-23 17:56:01 +08:00
|
|
|
|
"""估算当前缓存占用的内存大小(MB)"""
|
|
|
|
|
|
total_bytes = 0
|
|
|
|
|
|
|
|
|
|
|
|
for cached in self._cache.values():
|
|
|
|
|
|
for item in cached.values():
|
|
|
|
|
|
if isinstance(item, pd.DataFrame):
|
|
|
|
|
|
total_bytes += item.memory_usage(deep=True).sum()
|
|
|
|
|
|
elif isinstance(item, dict):
|
|
|
|
|
|
# 粗略估算字典大小
|
|
|
|
|
|
total_bytes += sum(
|
|
|
|
|
|
len(str(k)) + len(str(v)) for k, v in item.items()
|
|
|
|
|
|
)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-23 17:56:01 +08:00
|
|
|
|
return total_bytes / (1024 * 1024) # 转换为MB
|