2025-07-15 17:08:42 +08:00
|
|
|
import asyncio
|
|
|
|
|
import time
|
|
|
|
|
|
2025-08-22 02:43:19 +08:00
|
|
|
from zhenxun.services.cache import CacheRoot
|
2025-07-15 17:08:42 +08:00
|
|
|
from zhenxun.services.log import logger
|
|
|
|
|
|
|
|
|
|
from .config import (
|
|
|
|
|
DB_TIMEOUT_SECONDS,
|
|
|
|
|
LOG_COMMAND,
|
|
|
|
|
SLOW_QUERY_THRESHOLD,
|
|
|
|
|
)
|
|
|
|
|
|
2025-08-22 02:43:19 +08:00
|
|
|
cache = CacheRoot.cache_dict("DB_TEST", 10)
|
|
|
|
|
|
|
|
|
|
index = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
total = {}
|
|
|
|
|
|
2025-07-15 17:08:42 +08:00
|
|
|
|
|
|
|
|
async def with_db_timeout(
|
2025-08-22 02:43:19 +08:00
|
|
|
coro,
|
|
|
|
|
timeout: float = DB_TIMEOUT_SECONDS,
|
|
|
|
|
operation: str | None = None,
|
|
|
|
|
source: str | None = None,
|
2025-07-15 17:08:42 +08:00
|
|
|
):
|
|
|
|
|
"""带超时控制的数据库操作"""
|
2025-08-22 02:43:19 +08:00
|
|
|
global index, total, index2
|
2025-07-15 17:08:42 +08:00
|
|
|
start_time = time.time()
|
|
|
|
|
try:
|
2025-08-22 02:43:19 +08:00
|
|
|
if operation not in total:
|
|
|
|
|
total[operation] = CacheRoot.cache_dict(f"DB_TEST_{operation}", 10)
|
|
|
|
|
total[operation][str(index)] = "1"
|
|
|
|
|
index += 1
|
|
|
|
|
logger.info(f"当前数据库查询来源: {source}")
|
|
|
|
|
logger.info(
|
|
|
|
|
f"10秒内数据库查询次数 [{operation}]: {len(total[operation])}", "DB_TEST"
|
|
|
|
|
)
|
2025-07-15 17:08:42 +08:00
|
|
|
result = await asyncio.wait_for(coro, timeout=timeout)
|
2025-08-22 02:43:19 +08:00
|
|
|
cache[str(index)] = "1"
|
|
|
|
|
index += 1
|
2025-07-15 17:08:42 +08:00
|
|
|
elapsed = time.time() - start_time
|
|
|
|
|
if elapsed > SLOW_QUERY_THRESHOLD and operation:
|
|
|
|
|
logger.warning(f"慢查询: {operation} 耗时 {elapsed:.3f}s", LOG_COMMAND)
|
|
|
|
|
return result
|
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
|
if operation:
|
|
|
|
|
logger.error(f"数据库操作超时: {operation} (>{timeout}s)", LOG_COMMAND)
|
|
|
|
|
raise
|