更新 redis 异步存取

This commit is contained in:
Tian jianyong 2025-12-24 20:14:04 +08:00
parent 564c712e36
commit cd5fa88ec4

View File

@ -230,14 +230,14 @@ class SemanticCacheService:
chat_id=chat_id chat_id=chat_id
) )
existing = redis.get(cache_key) existing = await redis.get(cache_key)
if existing: if existing:
logger.debug(f"[SemanticCache] 问题已存在,跳过: {question[:30]}...") logger.debug(f"[SemanticCache] 问题已存在,跳过: {question[:30]}...")
return True return True
self._cleanup_old_cache(chat_id, redis) await self._cleanup_old_cache(chat_id, redis)
redis.set( await redis.set(
cache_key, cache_key,
json.dumps(entry.to_dict()), json.dumps(entry.to_dict()),
ex=self.CACHE_TTL_HOURS * 3600 ex=self.CACHE_TTL_HOURS * 3600
@ -245,7 +245,7 @@ class SemanticCacheService:
logger.info(f"[SemanticCache] 已缓存 | key={cache_key} | question={question[:30]}...") logger.info(f"[SemanticCache] 已缓存 | key={cache_key} | question={question[:30]}...")
verify = redis.get(cache_key) verify = await redis.get(cache_key)
logger.info(f"[SemanticCache] 存储验证 | key={cache_key} | found={verify is not None}") logger.info(f"[SemanticCache] 存储验证 | key={cache_key} | found={verify is not None}")
return True return True
@ -253,7 +253,7 @@ class SemanticCacheService:
logger.error(f"[SemanticCache] 存储失败: {e}") logger.error(f"[SemanticCache] 存储失败: {e}")
return False return False
def _cleanup_old_cache(self, chat_id: str, redis_client=None) -> int: async def _cleanup_old_cache(self, chat_id: str, redis_client=None) -> int:
""" """
清理旧缓存当缓存过多时 清理旧缓存当缓存过多时
@ -268,14 +268,14 @@ class SemanticCacheService:
try: try:
pattern = f"{self.CACHE_PREFIX}:{chat_id}:*" pattern = f"{self.CACHE_PREFIX}:{chat_id}:*"
cache_keys = redis.keys(pattern) cache_keys = await redis.keys(pattern)
if len(cache_keys) <= self.MAX_CACHE_SIZE: if len(cache_keys) <= self.MAX_CACHE_SIZE:
return 0 return 0
cache_info = [] cache_info = []
for key in cache_keys: for key in cache_keys:
data = redis.get(key) data = await redis.get(key)
if data: if data:
try: try:
entry = CacheEntry.from_dict(json.loads(data)) entry = CacheEntry.from_dict(json.loads(data))
@ -288,7 +288,7 @@ class SemanticCacheService:
deleted = 0 deleted = 0
for key, _ in cache_info[:delete_count]: for key, _ in cache_info[:delete_count]:
redis.delete(key) await redis.delete(key)
deleted += 1 deleted += 1
if deleted > 0: if deleted > 0: