- 支持三套独立环境:实盘(production)、回测(backtest)、模拟(simulation) - 环境完全隔离:独立数据库、Redis频道前缀、端口范围 - 配置系统改造: * 新增环境配置类(EnvironmentConfig)和频道配置类(RedisChannels) * 数据库名、Redis频道自动根据环境切换 * 支持从环境变量(CONFIG_FILE)加载配置 - Redis频道动态化: * RedisChannels类改为使用动态前缀 * 信号/订单频道使用统一配置 - 数据库初始化: * 创建三个独立数据库(QTrade_RealTrade/BackTestTrade/SimuTrade) * 提供Python初始化脚本 - 清理冗余代码: * 删除废弃的services配置目录 * 删除旧的启动脚本和初始化脚本 * 删除未使用的backtest目录 - 新增工具脚本: * start_services.py - 多环境服务启动 * init_databases.py - 数据库初始化 * test_config.py - 配置测试 环境映射: - production: DB=QTrade_RealTrade, Redis=real:, Port=9000+ - backtest: DB=QTrade_BackTestTrade, Redis=bt:, Port=10000+ - simulation: DB=QTrade_SimuTrade, Redis=simu:, Port=11000+
274 lines
7.7 KiB
Python
274 lines
7.7 KiB
Python
"""
|
||
配置管理工具类
|
||
|
||
统一管理配置文件的读取、保存和合并
|
||
配置加载优先级(从低到高):
|
||
1. global.yaml - 全局公共配置
|
||
2. services/{service_name}.yaml - 服务独立配置
|
||
3. 环境变量 - 运行时覆盖
|
||
|
||
使用示例:
|
||
# 加载配置
|
||
config = ConfigManager.load("data_service")
|
||
|
||
# 获取配置值
|
||
port = config.get("service.port", 8020)
|
||
|
||
# 修改并保存配置
|
||
config.set("service.port", 8021)
|
||
config.save()
|
||
"""
|
||
|
||
import os
|
||
from pathlib import Path
|
||
from typing import Any, Optional
|
||
|
||
import yaml
|
||
|
||
|
||
class ConfigManager:
|
||
"""配置管理器"""
|
||
|
||
def __init__(self, service_name: Optional[str] = None):
|
||
"""
|
||
初始化配置管理器
|
||
|
||
Args:
|
||
service_name: 服务名称,如 "data_service"、"qmt_service" 等
|
||
"""
|
||
self.service_name = service_name
|
||
self.project_root = self._get_project_root()
|
||
self.configs_dir = self.project_root / "configs"
|
||
|
||
# 支持从环境变量指定配置文件(用于多环境)
|
||
env_config_file = os.getenv("CONFIG_FILE")
|
||
if env_config_file:
|
||
# 使用环境变量指定的配置文件
|
||
self.env_config_path = self.project_root / env_config_file
|
||
else:
|
||
self.env_config_path = None
|
||
|
||
self.global_config_path = self.configs_dir / "global.yaml"
|
||
self.service_config_path = (
|
||
self.configs_dir / "services" / f"{service_name}.yaml"
|
||
if service_name
|
||
else None
|
||
)
|
||
|
||
# 存储合并后的配置
|
||
self._config: dict[str, Any] = {}
|
||
|
||
# 加载配置
|
||
self._load()
|
||
|
||
@staticmethod
|
||
def _get_project_root() -> Path:
|
||
"""获取项目根目录"""
|
||
current = Path(__file__).resolve()
|
||
for parent in [current] + list(current.parents):
|
||
if (parent / "configs").is_dir():
|
||
return parent
|
||
return Path.cwd()
|
||
|
||
def _load(self) -> None:
|
||
"""加载配置(按优先级合并)"""
|
||
# 优先级1: 环境配置文件(如果指定)
|
||
if self.env_config_path and self.env_config_path.exists():
|
||
self._config = self._load_yaml(self.env_config_path)
|
||
else:
|
||
# 优先级2: 加载全局配置
|
||
self._config = self._load_yaml(self.global_config_path)
|
||
|
||
# 优先级3: 加载服务配置并合并
|
||
if self.service_config_path and self.service_config_path.exists():
|
||
service_config = self._load_yaml(self.service_config_path)
|
||
self._deep_merge(self._config, service_config)
|
||
|
||
# 优先级4: 环境变量覆盖(格式:QTRADE_DATABASE_HOST=127.0.0.1)
|
||
self._apply_env_overrides()
|
||
|
||
def _load_yaml(self, path: Path) -> dict[str, Any]:
|
||
"""加载 YAML 文件"""
|
||
if not path.exists():
|
||
return {}
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
return yaml.safe_load(f) or {}
|
||
|
||
def _deep_merge(self, base: dict, override: dict) -> None:
|
||
"""深度合并字典(override 覆盖 base)"""
|
||
for key, value in override.items():
|
||
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
|
||
self._deep_merge(base[key], value)
|
||
else:
|
||
base[key] = value
|
||
|
||
def _apply_env_overrides(self) -> None:
|
||
"""应用环境变量覆盖(格式:QTRADE_DATABASE_HOST)"""
|
||
prefix = "QTRADE_"
|
||
for env_key, env_value in os.environ.items():
|
||
if not env_key.startswith(prefix):
|
||
continue
|
||
|
||
# 转换环境变量为配置路径
|
||
# QTRADE_DATABASE_HOST -> database.host
|
||
config_path = env_key[len(prefix) :].lower().replace("_", ".")
|
||
|
||
# 尝试智能类型转换
|
||
typed_value = self._convert_env_value(env_value, config_path)
|
||
self.set(config_path, typed_value)
|
||
|
||
def _convert_env_value(self, value: str, key: str) -> Any:
|
||
"""
|
||
智能转换环境变量值类型
|
||
|
||
Args:
|
||
value: 环境变量字符串值
|
||
key: 配置键路径
|
||
|
||
Returns:
|
||
转换后的值
|
||
"""
|
||
# 获取原始配置值,用于判断类型
|
||
original = self.get(key)
|
||
|
||
# 如果原始值是整数,尝试转换为整数
|
||
if isinstance(original, int):
|
||
try:
|
||
return int(value)
|
||
except ValueError:
|
||
pass
|
||
|
||
# 如果原始值是浮点数,尝试转换为浮点数
|
||
if isinstance(original, float):
|
||
try:
|
||
return float(value)
|
||
except ValueError:
|
||
pass
|
||
|
||
# 如果原始值是布尔值,转换为布尔值
|
||
if isinstance(original, bool):
|
||
return value.lower() in ("true", "1", "yes", "on")
|
||
|
||
# 默认返回字符串
|
||
return value
|
||
|
||
def get(self, key: str, default: Any = None) -> Any:
|
||
"""
|
||
获取配置值(支持点分路径)
|
||
|
||
Args:
|
||
key: 配置键,支持点分路径,如 "database.host"
|
||
default: 默认值
|
||
|
||
Returns:
|
||
配置值
|
||
"""
|
||
keys = key.split(".")
|
||
value = self._config
|
||
|
||
for k in keys:
|
||
if isinstance(value, dict) and k in value:
|
||
value = value[k]
|
||
else:
|
||
return default
|
||
|
||
return value
|
||
|
||
def set(self, key: str, value: Any) -> None:
|
||
"""
|
||
设置配置值(支持点分路径)
|
||
|
||
Args:
|
||
key: 配置键,支持点分路径,如 "database.host"
|
||
value: 配置值
|
||
"""
|
||
keys = key.split(".")
|
||
config = self._config
|
||
|
||
for k in keys[:-1]:
|
||
if k not in config or not isinstance(config[k], dict):
|
||
config[k] = {}
|
||
config = config[k]
|
||
|
||
config[keys[-1]] = value
|
||
|
||
def get_all(self) -> dict[str, Any]:
|
||
"""获取所有配置"""
|
||
return self._config.copy()
|
||
|
||
def save(self, target: str = "service") -> None:
|
||
"""
|
||
保存配置到文件
|
||
|
||
Args:
|
||
target: 保存目标,可选 "global" 或 "service"(默认)
|
||
"""
|
||
if target == "global":
|
||
save_path = self.global_config_path
|
||
elif target == "service" and self.service_config_path:
|
||
save_path = self.service_config_path
|
||
else:
|
||
raise ValueError(f"无效的保存目标: {target}")
|
||
|
||
# 确保目录存在
|
||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 保存到 YAML
|
||
with open(save_path, "w", encoding="utf-8") as f:
|
||
yaml.dump(self._config, f, allow_unicode=True, sort_keys=False)
|
||
|
||
@classmethod
|
||
def load(cls, service_name: Optional[str] = None) -> "ConfigManager":
|
||
"""
|
||
加载配置(类方法便捷入口)
|
||
|
||
Args:
|
||
service_name: 服务名称
|
||
|
||
Returns:
|
||
ConfigManager 实例
|
||
"""
|
||
return cls(service_name)
|
||
|
||
def __getitem__(self, key: str) -> Any:
|
||
"""支持字典式访问"""
|
||
return self.get(key)
|
||
|
||
def __setitem__(self, key: str, value: Any) -> None:
|
||
"""支持字典式赋值"""
|
||
self.set(key, value)
|
||
|
||
|
||
# 便捷函数
|
||
|
||
|
||
def load_config(service_name: Optional[str] = None) -> ConfigManager:
|
||
"""
|
||
加载配置
|
||
|
||
Args:
|
||
service_name: 服务名称,如 "data_service"
|
||
|
||
Returns:
|
||
ConfigManager 实例
|
||
"""
|
||
return ConfigManager.load(service_name)
|
||
|
||
|
||
def get_config_value(
|
||
key: str, service_name: Optional[str] = None, default: Any = None
|
||
) -> Any:
|
||
"""
|
||
快速获取配置值
|
||
|
||
Args:
|
||
key: 配置键
|
||
service_name: 服务名称
|
||
default: 默认值
|
||
|
||
Returns:
|
||
配置值
|
||
"""
|
||
config = ConfigManager.load(service_name)
|
||
return config.get(key, default)
|