feat: 重构配置系统,统一管理配置文件
- 创建 configs/global.yaml 存放全局公共配置
- 创建 configs/services/{service_name}.yaml 存放各服务独立配置
- 新增 ConfigManager 工具类,支持配置读取、保存和优先级合并
- 配置加载优先级:global.yaml < services/*.yaml < 环境变量
- 更新所有服务使用新配置系统
- 新增配置使用文档和测试脚本
- 移除旧的 Pydantic Settings 依赖,不保证兼容性
This commit is contained in:
parent
430660415f
commit
7e5e4d91fe
20
.env.example
20
.env.example
@ -1,20 +0,0 @@
|
|||||||
# QTrade 环境变量配置
|
|
||||||
# 复制此文件为 .env 并修改实际值
|
|
||||||
|
|
||||||
# 应用环境
|
|
||||||
QTRADE_ENV=development
|
|
||||||
|
|
||||||
# Redis
|
|
||||||
REDIS_HOST=127.0.0.1
|
|
||||||
REDIS_PORT=6379
|
|
||||||
REDIS_PASSWORD=
|
|
||||||
|
|
||||||
# MySQL
|
|
||||||
DB_HOST=127.0.0.1
|
|
||||||
DB_PORT=3306
|
|
||||||
DB_USER=root
|
|
||||||
DB_PASSWORD=1234
|
|
||||||
DB_NAME=qtrade
|
|
||||||
|
|
||||||
# 日志级别
|
|
||||||
LOG_LEVEL=INFO
|
|
||||||
76
configs/global.yaml
Normal file
76
configs/global.yaml
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
# QTrade 全局公共配置
|
||||||
|
# 说明: 此文件包含所有服务共用的配置项
|
||||||
|
|
||||||
|
# 应用配置
|
||||||
|
app:
|
||||||
|
name: "QTrade"
|
||||||
|
version: "2.0.0"
|
||||||
|
env: "development" # development, production
|
||||||
|
debug: true
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
redis:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 6379
|
||||||
|
password: ""
|
||||||
|
db: 0
|
||||||
|
pool_size: 10
|
||||||
|
pool_timeout: 30
|
||||||
|
|
||||||
|
# MySQL 配置
|
||||||
|
database:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 3306
|
||||||
|
user: "root"
|
||||||
|
password: "1234"
|
||||||
|
database: "qtrade_stock_data"
|
||||||
|
pool_size: 5
|
||||||
|
pool_recycle: 3600
|
||||||
|
echo: false
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level: "INFO" # DEBUG, INFO, WARNING, ERROR
|
||||||
|
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
file:
|
||||||
|
enabled: true
|
||||||
|
path: "logs"
|
||||||
|
max_size: 10485760 # 10MB
|
||||||
|
backup_count: 5
|
||||||
|
|
||||||
|
# 行情配置
|
||||||
|
market:
|
||||||
|
kline_periods:
|
||||||
|
- "1m"
|
||||||
|
- "5m"
|
||||||
|
- "15m"
|
||||||
|
- "30m"
|
||||||
|
- "60m"
|
||||||
|
- "1d"
|
||||||
|
- "1w"
|
||||||
|
cache_ttl: 60
|
||||||
|
|
||||||
|
# 交易配置
|
||||||
|
trading:
|
||||||
|
sessions:
|
||||||
|
morning:
|
||||||
|
start: "09:30"
|
||||||
|
end: "11:30"
|
||||||
|
afternoon:
|
||||||
|
start: "13:00"
|
||||||
|
end: "15:00"
|
||||||
|
|
||||||
|
# 服务端口配置(用于服务发现)
|
||||||
|
services:
|
||||||
|
core_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8010
|
||||||
|
data_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8020
|
||||||
|
strategy_engine:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8030
|
||||||
|
qmt_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8040
|
||||||
8
configs/services/core_service.yaml
Normal file
8
configs/services/core_service.yaml
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
# Core Service 配置
|
||||||
|
|
||||||
|
service:
|
||||||
|
name: "CoreService"
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8010
|
||||||
|
workers: 1
|
||||||
|
reload: true
|
||||||
17
configs/services/data_service.yaml
Normal file
17
configs/services/data_service.yaml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
# Data Service 配置
|
||||||
|
|
||||||
|
service:
|
||||||
|
name: "DataService"
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8020
|
||||||
|
workers: 1
|
||||||
|
reload: true # 开发模式自动重载
|
||||||
|
|
||||||
|
# 数据下载配置
|
||||||
|
data_download:
|
||||||
|
# 默认下载天数
|
||||||
|
default_days: 120
|
||||||
|
# 批量下载并发数
|
||||||
|
batch_size: 10
|
||||||
|
# 下载超时(秒)
|
||||||
|
timeout: 60
|
||||||
29
configs/services/qmt_service.yaml
Normal file
29
configs/services/qmt_service.yaml
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
# QMT Service 配置
|
||||||
|
|
||||||
|
service:
|
||||||
|
name: "QMTService"
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8040
|
||||||
|
workers: 1
|
||||||
|
reload: true
|
||||||
|
|
||||||
|
# QMT 客户端配置
|
||||||
|
qmt:
|
||||||
|
# QMT 客户端路径 (Mini QMT 安装目录)
|
||||||
|
path: "D:/国金证券QMT/userdata_mini"
|
||||||
|
# 会话 ID
|
||||||
|
session_id: 123456
|
||||||
|
# 资金账号
|
||||||
|
account_id: ""
|
||||||
|
# 是否启用模拟模式
|
||||||
|
simulation: true
|
||||||
|
# 数据中心 Token (用于 xtquant 独立数据下载)
|
||||||
|
data_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
|
||||||
|
# 优化地址列表
|
||||||
|
optimize_addresses:
|
||||||
|
- "115.231.218.73:55310"
|
||||||
|
- "115.231.218.79:55310"
|
||||||
|
- "218.16.123.11:55310"
|
||||||
|
- "218.16.123.27:55310"
|
||||||
|
# XtQuant 数据存储目录
|
||||||
|
data_home_dir: "caches/xtquant"
|
||||||
17
configs/services/strategy_engine.yaml
Normal file
17
configs/services/strategy_engine.yaml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
# Strategy Engine 配置
|
||||||
|
|
||||||
|
service:
|
||||||
|
name: "StrategyEngine"
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 8030
|
||||||
|
workers: 1
|
||||||
|
reload: true
|
||||||
|
|
||||||
|
# 策略引擎配置
|
||||||
|
strategy:
|
||||||
|
# 策略自动加载路径
|
||||||
|
auto_load_path: "src/strategies"
|
||||||
|
# 策略实例检查间隔(秒)
|
||||||
|
check_interval: 5
|
||||||
|
# 是否启用行情监听
|
||||||
|
enable_tick_listener: true
|
||||||
222
docs/config_guide.md
Normal file
222
docs/config_guide.md
Normal file
@ -0,0 +1,222 @@
|
|||||||
|
# QTrade 配置管理系统
|
||||||
|
|
||||||
|
## 配置文件结构
|
||||||
|
|
||||||
|
```
|
||||||
|
configs/
|
||||||
|
├── global.yaml # 全局公共配置
|
||||||
|
├── settings.yaml # 旧版配置(废弃,保留用于迁移)
|
||||||
|
└── services/ # 服务独立配置
|
||||||
|
├── core_service.yaml
|
||||||
|
├── data_service.yaml
|
||||||
|
├── strategy_engine.yaml
|
||||||
|
└── qmt_service.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置优先级
|
||||||
|
|
||||||
|
配置加载优先级(从低到高):
|
||||||
|
|
||||||
|
1. **global.yaml** - 全局公共配置(最低优先级)
|
||||||
|
2. **services/{service_name}.yaml** - 服务独立配置
|
||||||
|
3. **环境变量** - 运行时覆盖(最高优先级)
|
||||||
|
|
||||||
|
### 环境变量命名规则
|
||||||
|
|
||||||
|
环境变量格式:`QTRADE_{配置路径}`,路径用下划线分隔,例如:
|
||||||
|
|
||||||
|
- `QTRADE_DATABASE_HOST=192.168.1.100` → `database.host`
|
||||||
|
- `QTRADE_REDIS_PORT=6380` → `redis.port`
|
||||||
|
- `QTRADE_APP_ENV=production` → `app.env`
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
### 1. 加载全局配置
|
||||||
|
|
||||||
|
```python
|
||||||
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
print(settings.app.name) # QTrade
|
||||||
|
print(settings.redis.url) # redis://127.0.0.1:6379/0
|
||||||
|
print(settings.database.url) # mysql+aiomysql://...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 加载服务配置
|
||||||
|
|
||||||
|
```python
|
||||||
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
# 加载 data_service 配置
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
|
||||||
|
print(settings.service.name) # DataService
|
||||||
|
print(settings.service.port) # 8020
|
||||||
|
print(settings.data_download.default_days) # 120
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 修改并保存配置
|
||||||
|
|
||||||
|
```python
|
||||||
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings("qmt_service")
|
||||||
|
|
||||||
|
# 修改配置
|
||||||
|
settings.set("qmt.simulation", False)
|
||||||
|
settings.set("service.port", 8041)
|
||||||
|
|
||||||
|
# 保存到服务配置文件
|
||||||
|
settings.save("service") # 保存到 configs/services/qmt_service.yaml
|
||||||
|
|
||||||
|
# 保存到全局配置文件
|
||||||
|
settings.save("global") # 保存到 configs/global.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 直接使用 ConfigManager
|
||||||
|
|
||||||
|
```python
|
||||||
|
from src.core.config_manager import ConfigManager
|
||||||
|
|
||||||
|
# 加载配置
|
||||||
|
config = ConfigManager.load("strategy_engine")
|
||||||
|
|
||||||
|
# 获取值
|
||||||
|
port = config.get("service.port", 8030)
|
||||||
|
|
||||||
|
# 设置值
|
||||||
|
config.set("strategy.check_interval", 10)
|
||||||
|
|
||||||
|
# 保存
|
||||||
|
config.save()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 环境变量覆盖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在启动服务前设置环境变量
|
||||||
|
export QTRADE_DATABASE_HOST=prod.database.com
|
||||||
|
export QTRADE_REDIS_PORT=6380
|
||||||
|
export QTRADE_APP_ENV=production
|
||||||
|
|
||||||
|
python -m src.data_service.app
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置文件说明
|
||||||
|
|
||||||
|
### global.yaml
|
||||||
|
|
||||||
|
包含所有服务共用的配置:
|
||||||
|
- 应用信息(名称、版本、环境)
|
||||||
|
- Redis 配置
|
||||||
|
- MySQL 配置
|
||||||
|
- 日志配置
|
||||||
|
- 行情配置
|
||||||
|
- 交易配置
|
||||||
|
- 服务端口映射
|
||||||
|
|
||||||
|
### services/{service_name}.yaml
|
||||||
|
|
||||||
|
每个服务的独立配置:
|
||||||
|
|
||||||
|
**data_service.yaml**
|
||||||
|
- 服务基本信息(名称、端口)
|
||||||
|
- 数据下载配置
|
||||||
|
|
||||||
|
**qmt_service.yaml**
|
||||||
|
- 服务基本信息
|
||||||
|
- QMT 客户端配置
|
||||||
|
- XtQuant 数据中心配置
|
||||||
|
|
||||||
|
**strategy_engine.yaml**
|
||||||
|
- 服务基本信息
|
||||||
|
- 策略自动加载路径
|
||||||
|
- 策略实例检查间隔
|
||||||
|
|
||||||
|
**core_service.yaml**
|
||||||
|
- 服务基本信息
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **敏感信息使用环境变量**
|
||||||
|
```bash
|
||||||
|
export QTRADE_DATABASE_PASSWORD=your_password
|
||||||
|
export QTRADE_REDIS_PASSWORD=your_redis_password
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **开发/生产环境分离**
|
||||||
|
```bash
|
||||||
|
# 开发环境
|
||||||
|
export QTRADE_APP_ENV=development
|
||||||
|
|
||||||
|
# 生产环境
|
||||||
|
export QTRADE_APP_ENV=production
|
||||||
|
export QTRADE_DATABASE_HOST=prod.db.com
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **服务启动时加载对应配置**
|
||||||
|
```python
|
||||||
|
# data_service/app.py
|
||||||
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
|
||||||
|
uvicorn.run(
|
||||||
|
app,
|
||||||
|
host=settings.service.host,
|
||||||
|
port=settings.service.port
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **配置修改后保存**
|
||||||
|
```python
|
||||||
|
# 修改配置
|
||||||
|
settings.set("service.port", 8021)
|
||||||
|
|
||||||
|
# 保存到服务配置文件(推荐)
|
||||||
|
settings.save("service")
|
||||||
|
```
|
||||||
|
|
||||||
|
## 迁移指南
|
||||||
|
|
||||||
|
### 从旧版 settings.yaml 迁移
|
||||||
|
|
||||||
|
1. 将公共配置复制到 `global.yaml`
|
||||||
|
2. 将服务特定配置拆分到 `services/{service_name}.yaml`
|
||||||
|
3. 更新代码导入:
|
||||||
|
```python
|
||||||
|
# 旧版
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
# 新版
|
||||||
|
from src.core.config import get_settings
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
```
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
**Q: 如何查看当前生效的配置?**
|
||||||
|
|
||||||
|
```python
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
print(settings._manager.get_all())
|
||||||
|
```
|
||||||
|
|
||||||
|
**Q: 配置修改后如何重新加载?**
|
||||||
|
|
||||||
|
```python
|
||||||
|
settings.reload()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Q: 如何在不同环境使用不同配置?**
|
||||||
|
|
||||||
|
使用环境变量 `QTRADE_APP_ENV` 控制,并在代码中判断:
|
||||||
|
|
||||||
|
```python
|
||||||
|
settings = get_settings()
|
||||||
|
if settings.app.env == "production":
|
||||||
|
# 生产环境逻辑
|
||||||
|
else:
|
||||||
|
# 开发环境逻辑
|
||||||
|
```
|
||||||
131
examples/config_usage.py
Normal file
131
examples/config_usage.py
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
"""
|
||||||
|
配置管理示例
|
||||||
|
|
||||||
|
展示如何使用新的配置管理系统
|
||||||
|
"""
|
||||||
|
|
||||||
|
from src.core.config import get_settings, Settings
|
||||||
|
from src.core.config_manager import ConfigManager
|
||||||
|
|
||||||
|
|
||||||
|
def example_1_load_global_config():
|
||||||
|
"""示例1:加载全局配置"""
|
||||||
|
print("\n=== 示例1:加载全局配置 ===")
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
print(f"应用名称: {settings.app.name}")
|
||||||
|
print(f"环境: {settings.app.env}")
|
||||||
|
print(f"Redis URL: {settings.redis.url}")
|
||||||
|
print(f"数据库 URL: {settings.database.url}")
|
||||||
|
print(f"日志级别: {settings.logging.level}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_2_load_service_config():
|
||||||
|
"""示例2:加载服务配置"""
|
||||||
|
print("\n=== 示例2:加载服务配置 ===")
|
||||||
|
|
||||||
|
# 加载 data_service 配置
|
||||||
|
data_settings = get_settings("data_service")
|
||||||
|
|
||||||
|
print(f"服务名称: {data_settings.service.name}")
|
||||||
|
print(f"服务端口: {data_settings.service.port}")
|
||||||
|
print(f"默认下载天数: {data_settings.data_download.default_days}")
|
||||||
|
|
||||||
|
# 加载 qmt_service 配置
|
||||||
|
qmt_settings = get_settings("qmt_service")
|
||||||
|
|
||||||
|
print(f"\nQMT 服务端口: {qmt_settings.service.port}")
|
||||||
|
print(f"QMT 路径: {qmt_settings.qmt.path}")
|
||||||
|
print(f"模拟模式: {qmt_settings.qmt.simulation}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_3_modify_and_save():
|
||||||
|
"""示例3:修改并保存配置"""
|
||||||
|
print("\n=== 示例3:修改并保存配置 ===")
|
||||||
|
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
|
||||||
|
# 修改配置
|
||||||
|
old_port = settings.service.port
|
||||||
|
settings.set("service.port", 8021)
|
||||||
|
|
||||||
|
print(f"端口修改: {old_port} -> {settings.service.port}")
|
||||||
|
|
||||||
|
# 保存到服务配置文件
|
||||||
|
# settings.save("service") # 取消注释以实际保存
|
||||||
|
print("配置已保存(演示模式,未实际写入)")
|
||||||
|
|
||||||
|
# 恢复原值
|
||||||
|
settings.set("service.port", old_port)
|
||||||
|
|
||||||
|
|
||||||
|
def example_4_env_override():
|
||||||
|
"""示例4:环境变量覆盖"""
|
||||||
|
print("\n=== 示例4:环境变量覆盖 ===")
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 设置环境变量
|
||||||
|
os.environ["QTRADE_DATABASE_HOST"] = "192.168.1.100"
|
||||||
|
os.environ["QTRADE_REDIS_PORT"] = "6380"
|
||||||
|
|
||||||
|
# 重新加载配置
|
||||||
|
settings = Settings()
|
||||||
|
|
||||||
|
print(f"数据库主机: {settings.database.host}")
|
||||||
|
print(f"Redis 端口: {settings.redis.port}")
|
||||||
|
|
||||||
|
# 清理环境变量
|
||||||
|
del os.environ["QTRADE_DATABASE_HOST"]
|
||||||
|
del os.environ["QTRADE_REDIS_PORT"]
|
||||||
|
|
||||||
|
|
||||||
|
def example_5_direct_config_manager():
|
||||||
|
"""示例5:直接使用 ConfigManager"""
|
||||||
|
print("\n=== 示例5:直接使用 ConfigManager ===")
|
||||||
|
|
||||||
|
config = ConfigManager.load("strategy_engine")
|
||||||
|
|
||||||
|
# 获取配置
|
||||||
|
print(f"策略引擎端口: {config.get('service.port')}")
|
||||||
|
print(f"策略加载路径: {config.get('strategy.auto_load_path')}")
|
||||||
|
print(f"检查间隔: {config.get('strategy.check_interval')}")
|
||||||
|
|
||||||
|
# 获取所有配置
|
||||||
|
all_config = config.get_all()
|
||||||
|
print(f"\n配置键: {list(all_config.keys())}")
|
||||||
|
|
||||||
|
|
||||||
|
def example_6_config_priority():
|
||||||
|
"""示例6:配置优先级演示"""
|
||||||
|
print("\n=== 示例6:配置优先级 ===")
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 1. global.yaml 中定义了 database.host = "127.0.0.1"
|
||||||
|
# 2. 通过环境变量覆盖
|
||||||
|
os.environ["QTRADE_DATABASE_HOST"] = "prod.database.com"
|
||||||
|
|
||||||
|
settings = Settings()
|
||||||
|
|
||||||
|
print(f"最终数据库主机: {settings.database.host}")
|
||||||
|
print("优先级: 环境变量 > services/*.yaml > global.yaml")
|
||||||
|
|
||||||
|
# 清理
|
||||||
|
del os.environ["QTRADE_DATABASE_HOST"]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("QTrade 配置管理系统示例")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
example_1_load_global_config()
|
||||||
|
example_2_load_service_config()
|
||||||
|
example_3_modify_and_save()
|
||||||
|
example_4_env_override()
|
||||||
|
example_5_direct_config_manager()
|
||||||
|
example_6_config_priority()
|
||||||
|
|
||||||
|
print("\n" + "=" * 50)
|
||||||
|
print("示例运行完成!")
|
||||||
229
scripts/test_config.py
Normal file
229
scripts/test_config.py
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
"""
|
||||||
|
配置系统测试和验证脚本
|
||||||
|
|
||||||
|
检查配置文件是否正确加载,并验证配置优先级
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 添加项目根目录到路径
|
||||||
|
project_root = Path(__file__).resolve().parent.parent
|
||||||
|
sys.path.insert(0, str(project_root))
|
||||||
|
|
||||||
|
from src.core.config import get_settings, Settings
|
||||||
|
from src.core.config_manager import ConfigManager
|
||||||
|
|
||||||
|
|
||||||
|
def test_global_config():
|
||||||
|
"""测试全局配置加载"""
|
||||||
|
print("\n=== 测试全局配置 ===")
|
||||||
|
try:
|
||||||
|
settings = get_settings()
|
||||||
|
print(f"✓ 应用名称: {settings.app.name}")
|
||||||
|
print(f"✓ 环境: {settings.app.env}")
|
||||||
|
print(f"✓ Redis URL: {settings.redis.url}")
|
||||||
|
print(f"✓ 数据库 URL: {settings.database.url[:50]}...")
|
||||||
|
print(f"✓ 日志级别: {settings.logging.level}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ 全局配置加载失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_configs():
|
||||||
|
"""测试服务配置加载"""
|
||||||
|
print("\n=== 测试服务配置 ===")
|
||||||
|
services = ["data_service", "core_service", "strategy_engine", "qmt_service"]
|
||||||
|
|
||||||
|
for service_name in services:
|
||||||
|
try:
|
||||||
|
settings = get_settings(service_name)
|
||||||
|
port = settings.service.port
|
||||||
|
print(f"✓ {service_name}: 端口 {port}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ {service_name} 配置加载失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def test_specific_service_configs():
|
||||||
|
"""测试特定服务配置"""
|
||||||
|
print("\n=== 测试特定服务配置 ===")
|
||||||
|
|
||||||
|
# 测试 data_service 特有配置
|
||||||
|
try:
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
days = settings.data_download.default_days
|
||||||
|
print(f"✓ data_service 默认下载天数: {days}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ data_service 特有配置失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 测试 qmt_service 特有配置
|
||||||
|
try:
|
||||||
|
settings = get_settings("qmt_service")
|
||||||
|
simulation = settings.qmt.simulation
|
||||||
|
print(f"✓ qmt_service 模拟模式: {simulation}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ qmt_service 特有配置失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 测试 strategy_engine 特有配置
|
||||||
|
try:
|
||||||
|
settings = get_settings("strategy_engine")
|
||||||
|
interval = settings.strategy.check_interval
|
||||||
|
print(f"✓ strategy_engine 检查间隔: {interval}秒")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ strategy_engine 特有配置失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_priority():
|
||||||
|
"""测试配置优先级"""
|
||||||
|
print("\n=== 测试配置优先级 ===")
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
# 设置环境变量
|
||||||
|
os.environ["QTRADE_REDIS_PORT"] = "6380"
|
||||||
|
|
||||||
|
try:
|
||||||
|
settings = Settings()
|
||||||
|
port = settings.redis.port
|
||||||
|
|
||||||
|
if port == 6380:
|
||||||
|
print(f"✓ 环境变量覆盖成功: Redis 端口 = {port}")
|
||||||
|
result = True
|
||||||
|
else:
|
||||||
|
print(f"✗ 环境变量覆盖失败: 期望 6380, 实际 {port}")
|
||||||
|
result = False
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ 配置优先级测试失败: {e}")
|
||||||
|
result = False
|
||||||
|
finally:
|
||||||
|
# 清理环境变量
|
||||||
|
del os.environ["QTRADE_REDIS_PORT"]
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_paths():
|
||||||
|
"""测试配置文件路径"""
|
||||||
|
print("\n=== 测试配置文件路径 ===")
|
||||||
|
|
||||||
|
config = ConfigManager.load()
|
||||||
|
|
||||||
|
paths = {
|
||||||
|
"项目根目录": config.project_root,
|
||||||
|
"配置目录": config.configs_dir,
|
||||||
|
"全局配置": config.global_config_path,
|
||||||
|
}
|
||||||
|
|
||||||
|
all_exist = True
|
||||||
|
for name, path in paths.items():
|
||||||
|
if path.exists():
|
||||||
|
print(f"✓ {name}: {path}")
|
||||||
|
else:
|
||||||
|
print(f"✗ {name} 不存在: {path}")
|
||||||
|
all_exist = False
|
||||||
|
|
||||||
|
# 检查服务配置文件
|
||||||
|
services_dir = config.configs_dir / "services"
|
||||||
|
if services_dir.exists():
|
||||||
|
service_files = list(services_dir.glob("*.yaml"))
|
||||||
|
print(f"✓ 服务配置文件数量: {len(service_files)}")
|
||||||
|
for f in service_files:
|
||||||
|
print(f" - {f.name}")
|
||||||
|
else:
|
||||||
|
print(f"✗ 服务配置目录不存在: {services_dir}")
|
||||||
|
all_exist = False
|
||||||
|
|
||||||
|
return all_exist
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_manager_api():
|
||||||
|
"""测试 ConfigManager API"""
|
||||||
|
print("\n=== 测试 ConfigManager API ===")
|
||||||
|
|
||||||
|
try:
|
||||||
|
config = ConfigManager.load("data_service")
|
||||||
|
|
||||||
|
# 测试 get
|
||||||
|
port = config.get("service.port", 8020)
|
||||||
|
print(f"✓ get() 方法: 端口 = {port}")
|
||||||
|
|
||||||
|
# 测试 set
|
||||||
|
config.set("service.test_key", "test_value")
|
||||||
|
value = config.get("service.test_key")
|
||||||
|
if value == "test_value":
|
||||||
|
print(f"✓ set() 方法: 值 = {value}")
|
||||||
|
else:
|
||||||
|
print(f"✗ set() 方法失败")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 测试 get_all
|
||||||
|
all_config = config.get_all()
|
||||||
|
if isinstance(all_config, dict) and len(all_config) > 0:
|
||||||
|
print(f"✓ get_all() 方法: 配置键数量 = {len(all_config)}")
|
||||||
|
else:
|
||||||
|
print(f"✗ get_all() 方法失败")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ ConfigManager API 测试失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""运行所有测试"""
|
||||||
|
print("=" * 60)
|
||||||
|
print("QTrade 配置系统验证")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
tests = [
|
||||||
|
("配置文件路径", test_config_paths),
|
||||||
|
("全局配置", test_global_config),
|
||||||
|
("服务配置", test_service_configs),
|
||||||
|
("特定服务配置", test_specific_service_configs),
|
||||||
|
("配置优先级", test_config_priority),
|
||||||
|
("ConfigManager API", test_config_manager_api),
|
||||||
|
]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for name, test_func in tests:
|
||||||
|
try:
|
||||||
|
result = test_func()
|
||||||
|
results.append((name, result))
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n✗ {name} 测试异常: {e}")
|
||||||
|
results.append((name, False))
|
||||||
|
|
||||||
|
# 输出总结
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print("测试总结")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
passed = sum(1 for _, r in results if r)
|
||||||
|
total = len(results)
|
||||||
|
|
||||||
|
for name, result in results:
|
||||||
|
status = "✓ 通过" if result else "✗ 失败"
|
||||||
|
print(f"{status}: {name}")
|
||||||
|
|
||||||
|
print(f"\n通过: {passed}/{total}")
|
||||||
|
|
||||||
|
if passed == total:
|
||||||
|
print("\n🎉 所有测试通过!配置系统工作正常。")
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
print(f"\n⚠️ 有 {total - passed} 个测试失败,请检查配置。")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@ -1,307 +1,193 @@
|
|||||||
"""
|
"""
|
||||||
QTrade 配置管理模块
|
QTrade 配置管理模块
|
||||||
|
|
||||||
使用 Pydantic Settings 进行配置管理,支持:
|
使用统一的配置管理器进行配置管理,支持:
|
||||||
- YAML 配置文件
|
- 全局配置 (global.yaml)
|
||||||
|
- 服务独立配置 (services/{service_name}.yaml)
|
||||||
- 环境变量覆盖
|
- 环境变量覆盖
|
||||||
- 配置验证
|
- 配置验证
|
||||||
|
|
||||||
|
配置加载优先级(从低到高):
|
||||||
|
1. global.yaml - 全局公共配置
|
||||||
|
2. services/{service_name}.yaml - 服务独立配置
|
||||||
|
3. 环境变量 - 运行时覆盖
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import yaml
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
from .config_manager import ConfigManager
|
||||||
|
|
||||||
|
|
||||||
def get_project_root() -> Path:
|
def get_project_root() -> Path:
|
||||||
"""获取项目根目录"""
|
"""获取项目根目录"""
|
||||||
# 从当前文件向上查找,找到包含 configs 目录的位置
|
|
||||||
current = Path(__file__).resolve()
|
current = Path(__file__).resolve()
|
||||||
for parent in [current] + list(current.parents):
|
for parent in [current] + list(current.parents):
|
||||||
if (parent / "configs").is_dir():
|
if (parent / "configs").is_dir():
|
||||||
return parent
|
return parent
|
||||||
# 如果找不到,返回当前工作目录
|
|
||||||
return Path.cwd()
|
return Path.cwd()
|
||||||
|
|
||||||
|
|
||||||
def load_yaml_config(config_path: Path) -> dict[str, Any]:
|
# ========== 配置辅助类 ==========
|
||||||
"""加载 YAML 配置文件"""
|
|
||||||
if not config_path.exists():
|
|
||||||
return {}
|
|
||||||
with open(config_path, "r", encoding="utf-8") as f:
|
|
||||||
return yaml.safe_load(f) or {}
|
|
||||||
|
|
||||||
|
|
||||||
# ========== 使用 BaseModel 定义嵌套配置 ==========
|
class ConfigProxy:
|
||||||
|
"""配置代理类,提供便捷的属性访问"""
|
||||||
|
|
||||||
|
def __init__(self, config_manager: ConfigManager, prefix: str = ""):
|
||||||
|
self._manager = config_manager
|
||||||
|
self._prefix = prefix
|
||||||
|
|
||||||
|
def __getattr__(self, name: str) -> Any:
|
||||||
|
key = f"{self._prefix}.{name}" if self._prefix else name
|
||||||
|
value = self._manager.get(key)
|
||||||
|
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return ConfigProxy(self._manager, key)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def __getitem__(self, key: str) -> Any:
|
||||||
|
return self.__getattr__(key)
|
||||||
|
|
||||||
|
|
||||||
class RedisConfig(BaseModel):
|
class RedisConfig(ConfigProxy):
|
||||||
"""Redis 配置"""
|
"""Redis 配置"""
|
||||||
|
|
||||||
host: str = "127.0.0.1"
|
|
||||||
port: int = 6379
|
|
||||||
password: str = ""
|
|
||||||
db: int = 0
|
|
||||||
pool_size: int = 10
|
|
||||||
pool_timeout: int = 30
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def url(self) -> str:
|
def url(self) -> str:
|
||||||
"""生成 Redis URL"""
|
"""生成 Redis URL"""
|
||||||
auth = f":{self.password}@" if self.password else ""
|
password = self._manager.get("redis.password", "")
|
||||||
return f"redis://{auth}{self.host}:{self.port}/{self.db}"
|
host = self._manager.get("redis.host", "127.0.0.1")
|
||||||
|
port = self._manager.get("redis.port", 6379)
|
||||||
|
db = self._manager.get("redis.db", 0)
|
||||||
|
|
||||||
|
auth = f":{password}@" if password else ""
|
||||||
|
return f"redis://{auth}{host}:{port}/{db}"
|
||||||
|
|
||||||
|
|
||||||
class DatabaseConfig(BaseModel):
|
class DatabaseConfig(ConfigProxy):
|
||||||
"""数据库配置"""
|
"""数据库配置"""
|
||||||
|
|
||||||
host: str = "127.0.0.1"
|
|
||||||
port: int = 3306
|
|
||||||
user: str = "root"
|
|
||||||
password: str = ""
|
|
||||||
database: str = "qtrade"
|
|
||||||
pool_size: int = 5
|
|
||||||
pool_recycle: int = 3600
|
|
||||||
echo: bool = False
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def url(self) -> str:
|
def url(self) -> str:
|
||||||
"""生成数据库 URL (异步)"""
|
"""生成数据库 URL (异步)"""
|
||||||
|
user = self._manager.get("database.user", "root")
|
||||||
|
password = self._manager.get("database.password", "")
|
||||||
|
host = self._manager.get("database.host", "127.0.0.1")
|
||||||
|
port = self._manager.get("database.port", 3306)
|
||||||
|
database = self._manager.get("database.database", "qtrade")
|
||||||
|
|
||||||
return (
|
return (
|
||||||
f"mysql+aiomysql://{self.user}:{self.password}@"
|
f"mysql+aiomysql://{user}:{password}@"
|
||||||
f"{self.host}:{self.port}/{self.database}?charset=utf8mb4"
|
f"{host}:{port}/{database}?charset=utf8mb4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def sync_url(self) -> str:
|
def sync_url(self) -> str:
|
||||||
"""生成数据库 URL (同步,用于迁移)"""
|
"""生成数据库 URL (同步,用于迁移)"""
|
||||||
|
user = self._manager.get("database.user", "root")
|
||||||
|
password = self._manager.get("database.password", "")
|
||||||
|
host = self._manager.get("database.host", "127.0.0.1")
|
||||||
|
port = self._manager.get("database.port", 3306)
|
||||||
|
database = self._manager.get("database.database", "qtrade")
|
||||||
|
|
||||||
return (
|
return (
|
||||||
f"mysql+pymysql://{self.user}:{self.password}@"
|
f"mysql+pymysql://{user}:{password}@"
|
||||||
f"{self.host}:{self.port}/{self.database}?charset=utf8mb4"
|
f"{host}:{port}/{database}?charset=utf8mb4"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ServiceConfig(BaseModel):
|
class Settings:
|
||||||
"""单个服务配置"""
|
"""
|
||||||
|
统一配置类
|
||||||
|
|
||||||
host: str = "0.0.0.0"
|
使用 ConfigManager 加载配置,支持:
|
||||||
port: int
|
- 全局配置 (global.yaml)
|
||||||
|
- 服务配置 (services/{service_name}.yaml)
|
||||||
|
- 环境变量覆盖
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, service_name: str | None = None):
|
||||||
|
self._manager = ConfigManager(service_name)
|
||||||
|
self._service_name = service_name
|
||||||
|
|
||||||
class ServicesConfig(BaseModel):
|
# 创建配置代理
|
||||||
"""所有服务配置"""
|
self.app = ConfigProxy(self._manager, "app")
|
||||||
|
self.redis = RedisConfig(self._manager, "redis")
|
||||||
|
self.database = DatabaseConfig(self._manager, "database")
|
||||||
|
self.logging = ConfigProxy(self._manager, "logging")
|
||||||
|
self.market = ConfigProxy(self._manager, "market")
|
||||||
|
self.trading = ConfigProxy(self._manager, "trading")
|
||||||
|
|
||||||
core_service: ServiceConfig = ServiceConfig(port=8010)
|
# 服务配置
|
||||||
data_service: ServiceConfig = ServiceConfig(port=8020)
|
if service_name:
|
||||||
strategy_engine: ServiceConfig = ServiceConfig(port=8030)
|
self.service = ConfigProxy(self._manager, "service")
|
||||||
qmt_service: ServiceConfig = ServiceConfig(port=8040)
|
# QMT 服务特有配置
|
||||||
|
if service_name == "qmt_service":
|
||||||
|
self.qmt = ConfigProxy(self._manager, "qmt")
|
||||||
class QMTConfig(BaseModel):
|
# 策略引擎特有配置
|
||||||
"""QMT 配置"""
|
elif service_name == "strategy_engine":
|
||||||
|
self.strategy = ConfigProxy(self._manager, "strategy")
|
||||||
path: str = ""
|
# 数据服务特有配置
|
||||||
session_id: int = 123456
|
elif service_name == "data_service":
|
||||||
account_id: str = ""
|
self.data_download = ConfigProxy(self._manager, "data_download")
|
||||||
simulation: bool = True
|
else:
|
||||||
data_token: str = "" # XtQuant 数据中心 Token
|
# 加载所有服务端口配置(兼容旧代码)
|
||||||
optimize_addresses: list[str] = [] # 数据中心优化地址
|
self.services = ConfigProxy(self._manager, "services")
|
||||||
data_home_dir: str = "caches/xtquant" # XtQuant 数据存储目录
|
|
||||||
|
|
||||||
|
|
||||||
class LoggingFileConfig(BaseModel):
|
|
||||||
"""日志文件配置"""
|
|
||||||
|
|
||||||
enabled: bool = True
|
|
||||||
path: str = "logs"
|
|
||||||
max_size: int = 10485760 # 10MB
|
|
||||||
backup_count: int = 5
|
|
||||||
|
|
||||||
|
|
||||||
class LoggingConfig(BaseModel):
|
|
||||||
"""日志配置"""
|
|
||||||
|
|
||||||
level: str = "INFO"
|
|
||||||
format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
||||||
file: LoggingFileConfig = LoggingFileConfig()
|
|
||||||
|
|
||||||
|
|
||||||
class MarketConfig(BaseModel):
|
|
||||||
"""行情配置"""
|
|
||||||
|
|
||||||
kline_periods: list[str] = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"]
|
|
||||||
cache_ttl: int = 60
|
|
||||||
|
|
||||||
|
|
||||||
class TradingSessionConfig(BaseModel):
|
|
||||||
"""交易时段配置"""
|
|
||||||
|
|
||||||
start: str
|
|
||||||
end: str
|
|
||||||
|
|
||||||
|
|
||||||
class TradingSessionsConfig(BaseModel):
|
|
||||||
"""交易时段集合"""
|
|
||||||
|
|
||||||
morning: TradingSessionConfig = TradingSessionConfig(start="09:30", end="11:30")
|
|
||||||
afternoon: TradingSessionConfig = TradingSessionConfig(start="13:00", end="15:00")
|
|
||||||
|
|
||||||
|
|
||||||
class RiskConfig(BaseModel):
|
|
||||||
"""风控配置"""
|
|
||||||
|
|
||||||
max_position_ratio: float = 0.3
|
|
||||||
max_order_value: float = 1000000
|
|
||||||
|
|
||||||
|
|
||||||
class TradingConfig(BaseModel):
|
|
||||||
"""交易配置"""
|
|
||||||
|
|
||||||
sessions: TradingSessionsConfig = TradingSessionsConfig()
|
|
||||||
risk: RiskConfig = RiskConfig()
|
|
||||||
|
|
||||||
|
|
||||||
class AppConfig(BaseModel):
|
|
||||||
"""应用配置"""
|
|
||||||
|
|
||||||
name: str = "QTrade"
|
|
||||||
version: str = "2.0.0"
|
|
||||||
env: str = "development"
|
|
||||||
debug: bool = True
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_production(self) -> bool:
|
def project_root(self) -> Path:
|
||||||
return self.env == "production"
|
"""项目根目录"""
|
||||||
|
return self._manager.project_root
|
||||||
|
|
||||||
# ========== 主配置类 ==========
|
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
|
||||||
"""
|
|
||||||
主配置类
|
|
||||||
|
|
||||||
配置优先级(从高到低):
|
|
||||||
1. 环境变量
|
|
||||||
2. YAML 配置文件
|
|
||||||
3. 默认值
|
|
||||||
|
|
||||||
环境变量映射:
|
|
||||||
- QTRADE_ENV -> app.env
|
|
||||||
- REDIS_HOST -> redis.host
|
|
||||||
- DB_HOST -> database.host
|
|
||||||
- LOG_LEVEL -> logging.level
|
|
||||||
"""
|
|
||||||
|
|
||||||
model_config = SettingsConfigDict(
|
|
||||||
env_file=".env",
|
|
||||||
env_file_encoding="utf-8",
|
|
||||||
extra="ignore",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 嵌套配置
|
|
||||||
app: AppConfig = AppConfig()
|
|
||||||
redis: RedisConfig = RedisConfig()
|
|
||||||
database: DatabaseConfig = DatabaseConfig()
|
|
||||||
services: ServicesConfig = ServicesConfig()
|
|
||||||
logging: LoggingConfig = LoggingConfig()
|
|
||||||
market: MarketConfig = MarketConfig()
|
|
||||||
trading: TradingConfig = TradingConfig()
|
|
||||||
qmt: QMTConfig = QMTConfig()
|
|
||||||
|
|
||||||
# 项目路径
|
|
||||||
project_root: Path = Field(default_factory=get_project_root)
|
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
|
||||||
# 先加载 YAML 配置
|
|
||||||
yaml_config = _load_yaml_config()
|
|
||||||
|
|
||||||
# 处理环境变量覆盖
|
|
||||||
env_overrides = _get_env_overrides()
|
|
||||||
|
|
||||||
# 合并配置: 默认值 < YAML < 环境变量 < kwargs
|
|
||||||
merged = _deep_merge(yaml_config, env_overrides)
|
|
||||||
merged = _deep_merge(merged, kwargs)
|
|
||||||
|
|
||||||
super().__init__(**merged)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def logs_dir(self) -> Path:
|
def logs_dir(self) -> Path:
|
||||||
"""日志目录"""
|
"""日志目录"""
|
||||||
logs_path = self.project_root / self.logging.file.path
|
log_path = self._manager.get("logging.file.path", "logs")
|
||||||
|
logs_path = self.project_root / log_path
|
||||||
logs_path.mkdir(parents=True, exist_ok=True)
|
logs_path.mkdir(parents=True, exist_ok=True)
|
||||||
return logs_path
|
return logs_path
|
||||||
|
|
||||||
|
def get(self, key: str, default: Any = None) -> Any:
|
||||||
|
"""获取配置值"""
|
||||||
|
return self._manager.get(key, default)
|
||||||
|
|
||||||
def _load_yaml_config() -> dict[str, Any]:
|
def set(self, key: str, value: Any) -> None:
|
||||||
"""加载 YAML 配置"""
|
"""设置配置值"""
|
||||||
config_path = get_project_root() / "configs" / "settings.yaml"
|
self._manager.set(key, value)
|
||||||
return load_yaml_config(config_path)
|
|
||||||
|
def save(self, target: str = "service") -> None:
|
||||||
|
"""保存配置"""
|
||||||
|
self._manager.save(target)
|
||||||
|
|
||||||
|
def reload(self) -> None:
|
||||||
|
"""重新加载配置"""
|
||||||
|
self._manager._load()
|
||||||
|
|
||||||
|
|
||||||
def _get_env_overrides() -> dict[str, Any]:
|
# 全局配置实例(默认无服务名,加载全局配置)
|
||||||
"""从环境变量获取配置覆盖"""
|
|
||||||
overrides: dict[str, Any] = {}
|
|
||||||
|
|
||||||
# 应用环境
|
|
||||||
if env := os.getenv("QTRADE_ENV"):
|
|
||||||
overrides.setdefault("app", {})["env"] = env
|
|
||||||
|
|
||||||
# Redis
|
|
||||||
if host := os.getenv("REDIS_HOST"):
|
|
||||||
overrides.setdefault("redis", {})["host"] = host
|
|
||||||
if port := os.getenv("REDIS_PORT"):
|
|
||||||
overrides.setdefault("redis", {})["port"] = int(port)
|
|
||||||
if password := os.getenv("REDIS_PASSWORD"):
|
|
||||||
overrides.setdefault("redis", {})["password"] = password
|
|
||||||
if db := os.getenv("REDIS_DB"):
|
|
||||||
overrides.setdefault("redis", {})["db"] = int(db)
|
|
||||||
|
|
||||||
# 数据库
|
|
||||||
if host := os.getenv("DB_HOST"):
|
|
||||||
overrides.setdefault("database", {})["host"] = host
|
|
||||||
if port := os.getenv("DB_PORT"):
|
|
||||||
overrides.setdefault("database", {})["port"] = int(port)
|
|
||||||
if user := os.getenv("DB_USER"):
|
|
||||||
overrides.setdefault("database", {})["user"] = user
|
|
||||||
if password := os.getenv("DB_PASSWORD"):
|
|
||||||
overrides.setdefault("database", {})["password"] = password
|
|
||||||
if name := os.getenv("DB_NAME"):
|
|
||||||
overrides.setdefault("database", {})["database"] = name
|
|
||||||
|
|
||||||
# 日志
|
|
||||||
if level := os.getenv("LOG_LEVEL"):
|
|
||||||
overrides.setdefault("logging", {})["level"] = level
|
|
||||||
|
|
||||||
return overrides
|
|
||||||
|
|
||||||
|
|
||||||
def _deep_merge(base: dict, override: dict) -> dict:
|
|
||||||
"""深度合并字典"""
|
|
||||||
result = base.copy()
|
|
||||||
for key, value in override.items():
|
|
||||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
||||||
result[key] = _deep_merge(result[key], value)
|
|
||||||
else:
|
|
||||||
result[key] = value
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
# 全局配置实例
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|
||||||
|
|
||||||
# 便捷访问
|
# 便捷函数
|
||||||
def get_settings() -> Settings:
|
def get_settings(service_name: str | None = None) -> Settings:
|
||||||
"""获取配置实例"""
|
"""
|
||||||
return settings
|
获取配置实例
|
||||||
|
|
||||||
|
Args:
|
||||||
|
service_name: 服务名称,如 "data_service"、"qmt_service" 等
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Settings 实例
|
||||||
|
"""
|
||||||
|
return Settings(service_name)
|
||||||
|
|
||||||
|
|
||||||
def reload_settings() -> Settings:
|
def reload_settings() -> Settings:
|
||||||
"""重新加载配置"""
|
"""重新加载全局配置"""
|
||||||
global settings
|
global settings
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
return settings
|
return settings
|
||||||
|
|||||||
222
src/core/config_manager.py
Normal file
222
src/core/config_manager.py
Normal file
@ -0,0 +1,222 @@
|
|||||||
|
"""
|
||||||
|
配置管理工具类
|
||||||
|
|
||||||
|
统一管理配置文件的读取、保存和合并
|
||||||
|
配置加载优先级(从低到高):
|
||||||
|
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)
|
||||||
@ -11,7 +11,10 @@ Core Service FastAPI 应用
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from src.core.base_app import BaseApp
|
from src.core.base_app import BaseApp
|
||||||
from src.core.config import settings
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
# 加载服务配置
|
||||||
|
settings = get_settings("core_service")
|
||||||
|
|
||||||
|
|
||||||
class CoreServiceApp(BaseApp):
|
class CoreServiceApp(BaseApp):
|
||||||
|
|||||||
@ -10,7 +10,10 @@ Data Service FastAPI 应用
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from src.core.base_app import BaseApp
|
from src.core.base_app import BaseApp
|
||||||
from src.core.config import settings
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
# 加载服务配置
|
||||||
|
settings = get_settings("data_service")
|
||||||
|
|
||||||
|
|
||||||
class DataServiceApp(BaseApp):
|
class DataServiceApp(BaseApp):
|
||||||
|
|||||||
@ -10,7 +10,10 @@ QMT 服务:
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from src.core.base_app import BaseApp
|
from src.core.base_app import BaseApp
|
||||||
from src.core.config import settings
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
# 加载服务配置
|
||||||
|
settings = get_settings("qmt_service")
|
||||||
|
|
||||||
|
|
||||||
class QMTServiceApp(BaseApp):
|
class QMTServiceApp(BaseApp):
|
||||||
|
|||||||
@ -9,9 +9,12 @@ from fastapi import APIRouter, HTTPException
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from src.core.config import settings
|
from src.core.config import get_settings
|
||||||
from src.core.logger import get_logger
|
from src.core.logger import get_logger
|
||||||
|
|
||||||
|
# 加载服务配置
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|||||||
@ -10,7 +10,10 @@ Strategy Engine 应用入口
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from src.core.base_app import BaseApp
|
from src.core.base_app import BaseApp
|
||||||
from src.core.config import settings
|
from src.core.config import get_settings
|
||||||
|
|
||||||
|
# 加载服务配置
|
||||||
|
settings = get_settings("strategy_engine")
|
||||||
|
|
||||||
|
|
||||||
class StrategyEngineApp(BaseApp):
|
class StrategyEngineApp(BaseApp):
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user