2024-10-22 23:22:01 +02:00
|
|
|
|
import asyncio
|
|
|
|
|
import json
|
|
|
|
|
import hashlib
|
|
|
|
|
import logging
|
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
|
|
import redis.asyncio as aioredis
|
2024-10-22 22:51:03 +02:00
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
2024-10-22 23:22:01 +02:00
|
|
|
|
logger = logging.getLogger(__name__)
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
class RedisCache:
|
|
|
|
|
def __init__(self):
|
2024-10-22 23:22:01 +02:00
|
|
|
|
self.redis: Optional[aioredis.Redis] = None
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
async def connect(self):
|
2024-10-22 23:22:01 +02:00
|
|
|
|
if not self.redis:
|
|
|
|
|
self.redis = aioredis.from_url(settings.REDIS_URL, encoding="utf-8", decode_responses=True)
|
|
|
|
|
logger.info("Подключение к Redis установлено.")
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
async def disconnect(self):
|
|
|
|
|
if self.redis:
|
|
|
|
|
await self.redis.close()
|
2024-10-22 23:22:01 +02:00
|
|
|
|
logger.info("Подключение к Redis закрыто.")
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
async def get(self, key: str):
|
|
|
|
|
if not self.redis:
|
|
|
|
|
await self.connect()
|
2024-10-22 23:22:01 +02:00
|
|
|
|
value = await self.redis.get(key)
|
|
|
|
|
logger.debug(f"Получено из кеша по ключу {key}: {value}")
|
|
|
|
|
return value
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
async def set(self, key: str, value: str, expire: int = 3600):
|
|
|
|
|
if not self.redis:
|
|
|
|
|
await self.connect()
|
|
|
|
|
await self.redis.set(key, value, ex=expire)
|
2024-10-22 23:22:01 +02:00
|
|
|
|
logger.debug(f"Сохранено в кеш по ключу {key}: {value} с истечением {expire} секунд")
|
2024-10-22 22:51:03 +02:00
|
|
|
|
|
|
|
|
|
cache = RedisCache()
|