fix: Redis 缓存构造修正 + TTL=0 永不过期支持

- main.py: 先创建 aioredis 客户端再传入 RedisResponseCache
- redis_cache.py: ttl_s=None 时不设过期时间
- .env: REDIS_CACHE_TTL=0(永不过期)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-09 13:52:33 -04:00
parent 953fb7a456
commit d6ae0d85cd
2 changed files with 10 additions and 4 deletions
+5 -2
View File
@@ -22,10 +22,10 @@ class RedisResponseCache:
Args:
redis: 异步 Redis 客户端实例(duck-typed,需支持 get/set 方法)。
ttl_s: 缓存过期时间(秒)。
ttl_s: 缓存过期时间(秒)。None 表示永不过期。
"""
def __init__(self, redis: Any, ttl_s: int) -> None:
def __init__(self, redis: Any, ttl_s: int | None) -> None:
self._redis = redis
self._ttl_s = ttl_s
@@ -86,6 +86,9 @@ class RedisResponseCache:
try:
key = self._build_key(model, messages)
value = json.dumps(dataclasses.asdict(response), ensure_ascii=False)
if self._ttl_s:
await self._redis.set(key, value, ex=self._ttl_s)
else:
await self._redis.set(key, value)
except Exception:
logger.warning("Redis 缓存写入失败,跳过缓存")
+4 -1
View File
@@ -85,9 +85,12 @@ def _build_adapters(settings: InfraSettings, embed_cfg: dict) -> _Adapters:
cache = None
if settings.redis_url:
try:
import redis.asyncio as aioredis
from adapters.redis_cache import RedisResponseCache
cache = RedisResponseCache(redis_url=settings.redis_url, ttl=settings.redis_cache_ttl)
redis_client = aioredis.from_url(settings.redis_url, decode_responses=True)
ttl_s = settings.redis_cache_ttl if settings.redis_cache_ttl > 0 else None
cache = RedisResponseCache(redis=redis_client, ttl_s=ttl_s)
except Exception:
logger.warning("Redis 缓存不可用,降级为无缓存模式")