zhenxun_bot/zhenxun/services/db_context/utils.py
HibiKier a8ee63b199 🔧 修复和优化:调整超时设置,重构检查逻辑,简化代码结构
- 在 `chkdsk_hook.py` 中重构 `check` 方法,提取公共逻辑
- 更新 `CacheManager` 中的超时设置,使用新的 `CACHE_TIMEOUT`
- 在 `utils.py` 中添加缓存逻辑,记录数据库操作的执行情况
2025-09-30 15:54:21 +08:00

45 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import random
import time
from zhenxun.services.log import logger
from ..cache import CacheRoot
from .config import (
DB_TIMEOUT_SECONDS,
LOG_COMMAND,
SLOW_QUERY_THRESHOLD,
)
aaa = CacheRoot.cache_dict("AAA", 10, int)
async def with_db_timeout(
coro,
timeout: float = DB_TIMEOUT_SECONDS,
operation: str | None = None,
source: str | None = None,
):
"""带超时控制的数据库操作"""
start_time = time.time()
try:
logger.debug(f"开始执行数据库操作: {operation} 来源: {source}")
result = await asyncio.wait_for(coro, timeout=timeout)
aaa[str(random.randint(0, 100000))] = 1
elapsed = time.time() - start_time
if elapsed > SLOW_QUERY_THRESHOLD and operation:
logger.warning(f"慢查询: {operation} 耗时 {elapsed:.3f}s", LOG_COMMAND)
logger.debug(
f"10s内数据库查询次数: {len(aaa)} 开始执行数据库操作: {operation} "
f"来源: {source}, 当次返回数据ID: {getattr(result, 'id', None)}",
LOG_COMMAND,
)
return result
except asyncio.TimeoutError:
if operation:
logger.error(
f"数据库操作超时: {operation} (>{timeout}s) 来源: {source}",
LOG_COMMAND,
)
raise