71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
import json
|
|
from typing import Optional, List, Dict, Any
|
|
import redis.asyncio as redis
|
|
from app.core.config import settings
|
|
|
|
|
|
class CacheService:
|
|
def __init__(self):
|
|
self.redis_client: Optional[redis.Redis] = None
|
|
|
|
async def connect(self):
|
|
"""Подключение к Redis"""
|
|
self.redis_client = await redis.from_url(
|
|
settings.redis_url,
|
|
encoding="utf-8",
|
|
decode_responses=True
|
|
)
|
|
|
|
async def disconnect(self):
|
|
"""Отключение от Redis"""
|
|
if self.redis_client:
|
|
await self.redis_client.close()
|
|
|
|
async def get(self, key: str) -> Optional[str]:
|
|
"""Получить значение по ключу"""
|
|
if not self.redis_client:
|
|
await self.connect()
|
|
return await self.redis_client.get(key)
|
|
|
|
async def set(self, key: str, value: str, expire: int = 3600):
|
|
"""Установить значение с TTL"""
|
|
if not self.redis_client:
|
|
await self.connect()
|
|
await self.redis_client.setex(key, expire, value)
|
|
|
|
async def delete(self, key: str):
|
|
"""Удалить ключ"""
|
|
if not self.redis_client:
|
|
await self.connect()
|
|
await self.redis_client.delete(key)
|
|
|
|
async def get_conversation_context(
|
|
self,
|
|
conversation_id: str
|
|
) -> List[Dict[str, Any]]:
|
|
"""Получить контекст разговора"""
|
|
key = f"conversation:{conversation_id}"
|
|
data = await self.get(key)
|
|
if data:
|
|
return json.loads(data)
|
|
return []
|
|
|
|
async def save_conversation_context(
|
|
self,
|
|
conversation_id: str,
|
|
context: List[Dict[str, Any]],
|
|
expire: int = 86400 * 7 # 7 дней
|
|
):
|
|
"""Сохранить контекст разговора"""
|
|
key = f"conversation:{conversation_id}"
|
|
await self.set(key, json.dumps(context), expire=expire)
|
|
|
|
async def cache_token(self, token: str, expire: int = 1800):
|
|
"""Кэшировать токен (для rate limiting)"""
|
|
key = f"token:{token}"
|
|
await self.set(key, "1", expire=expire)
|
|
|
|
|
|
cache_service = CacheService()
|
|
|