Files
New-planet-api/new-planet-backend/app/services/cache_service.py
2025-12-13 14:39:50 +03:00

71 lines
2.2 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 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()