- 创建 configs/global.yaml 存放全局公共配置
- 创建 configs/services/{service_name}.yaml 存放各服务独立配置
- 新增 ConfigManager 工具类,支持配置读取、保存和优先级合并
- 配置加载优先级:global.yaml < services/*.yaml < 环境变量
- 更新所有服务使用新配置系统
- 新增配置使用文档和测试脚本
- 移除旧的 Pydantic Settings 依赖,不保证兼容性
223 lines
6.1 KiB
Python
223 lines
6.1 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"
|
||
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. 加载全局配置
|
||
self._config = self._load_yaml(self.global_config_path)
|
||
|
||
# 2. 加载服务配置并合并
|
||
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)
|
||
|
||
# 3. 环境变量覆盖(格式: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("_", ".")
|
||
self.set(config_path, env_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)
|