add
This commit is contained in:
0
utils/__init__.py
Normal file
0
utils/__init__.py
Normal file
75
utils/database_manager.py
Normal file
75
utils/database_manager.py
Normal file
@@ -0,0 +1,75 @@
|
||||
from sqlalchemy import create_engine, select, update, insert, delete, and_, or_, text
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from loguru import logger
|
||||
from typing import List, Dict, Optional, Any
|
||||
import json
|
||||
|
||||
from config.database import DATABASE_CONFIG, SQLALCHEMY_CONFIG
|
||||
from models.orm_models import Base, StrategyPosition, StrategyOrder, StrategyKX
|
||||
|
||||
class DatabaseManager:
|
||||
"""数据库管理器"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if not self._initialized:
|
||||
self._engine = None
|
||||
self._session_factory = None
|
||||
self._initialized = True
|
||||
self._init_engine()
|
||||
|
||||
def _init_engine(self):
|
||||
"""初始化数据库引擎"""
|
||||
try:
|
||||
# 构建数据库URL
|
||||
db_url = (
|
||||
f"mysql+pymysql://{DATABASE_CONFIG['user']}:{DATABASE_CONFIG['password']}"
|
||||
f"@{DATABASE_CONFIG['host']}:{DATABASE_CONFIG['port']}"
|
||||
f"/{DATABASE_CONFIG['database']}?charset={DATABASE_CONFIG['charset']}"
|
||||
)
|
||||
|
||||
# 创建引擎
|
||||
self._engine = create_engine(
|
||||
db_url,
|
||||
echo=SQLALCHEMY_CONFIG['echo'],
|
||||
echo_pool=SQLALCHEMY_CONFIG['echo_pool'],
|
||||
pool_size=DATABASE_CONFIG['pool_size'],
|
||||
max_overflow=DATABASE_CONFIG['max_overflow'],
|
||||
pool_recycle=DATABASE_CONFIG['pool_recycle'],
|
||||
pool_pre_ping=SQLALCHEMY_CONFIG['pool_pre_ping']
|
||||
)
|
||||
|
||||
# 创建会话工厂
|
||||
self._session_factory = sessionmaker(
|
||||
bind=self._engine,
|
||||
expire_on_commit=False
|
||||
)
|
||||
|
||||
# 创建表(如果不存在)
|
||||
Base.metadata.create_all(self._engine)
|
||||
|
||||
logger.info("SQLAlchemy数据库引擎初始化成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库引擎初始化失败: {e}")
|
||||
raise
|
||||
|
||||
def get_session(self) -> Session:
|
||||
"""获取数据库会话"""
|
||||
if self._session_factory is None:
|
||||
self._init_engine()
|
||||
return self._session_factory()
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if self._engine:
|
||||
self._engine.dispose()
|
||||
logger.info("数据库连接已关闭")
|
||||
0
utils/helpers.py
Normal file
0
utils/helpers.py
Normal file
54
utils/redis_client.py
Normal file
54
utils/redis_client.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import redis
|
||||
from loguru import logger
|
||||
from config.settings import REDIS_CONFIG
|
||||
|
||||
class RedisClient:
|
||||
"""Redis客户端管理器"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if not self._initialized:
|
||||
self._pool = None
|
||||
self._client = None
|
||||
self._initialized = True
|
||||
|
||||
@property
|
||||
def client(self):
|
||||
"""获取Redis客户端(懒加载)"""
|
||||
if self._client is None:
|
||||
self._init_connection_pool()
|
||||
return self._client
|
||||
|
||||
def _init_connection_pool(self):
|
||||
"""初始化连接池"""
|
||||
try:
|
||||
self._pool = redis.ConnectionPool(
|
||||
host=REDIS_CONFIG['host'],
|
||||
port=REDIS_CONFIG['port'],
|
||||
db=REDIS_CONFIG['db'],
|
||||
decode_responses=REDIS_CONFIG['decode_responses'],
|
||||
max_connections=REDIS_CONFIG['max_connections'],
|
||||
socket_keepalive=True
|
||||
)
|
||||
self._client = redis.Redis(connection_pool=self._pool)
|
||||
|
||||
# 测试连接
|
||||
self._client.ping()
|
||||
logger.info("Redis连接池初始化成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Redis连接失败: {e}")
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
"""关闭连接池"""
|
||||
if self._pool:
|
||||
self._pool.disconnect()
|
||||
logger.info("Redis连接池已关闭")
|
||||
Reference in New Issue
Block a user