File size: 2,096 Bytes
7a5b513
 
 
 
 
 
 
755d6cd
7a5b513
755d6cd
7a5b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Cache module for Auth microservice - Redis connection and caching utilities
"""
import redis
from typing import Optional, Any
import json
from app.core.config import settings
from app.core.logging import get_logger

logger = get_logger(__name__)


class CacheService:
    """Redis cache service for authentication system"""
    
    def __init__(self):
        self._redis_client: Optional[redis.Redis] = None
    
    def get_client(self) -> redis.Redis:
        """Get Redis client instance"""
        if self._redis_client is None:
            self._redis_client = redis.Redis(
                host=settings.REDIS_HOST,
                port=settings.REDIS_PORT,
                password=settings.REDIS_PASSWORD,
                db=settings.REDIS_DB,
                decode_responses=True
            )
        return self._redis_client
    
    async def set(self, key: str, value: Any, ttl: int = 300) -> bool:
        """Set a value in cache with TTL"""
        try:
            client = self.get_client()
            serialized_value = json.dumps(value) if not isinstance(value, str) else value
            return client.setex(key, ttl, serialized_value)
        except Exception as e:
            logger.error(f"Cache set error: {e}")
            return False
    
    async def get(self, key: str) -> Optional[Any]:
        """Get a value from cache"""
        try:
            client = self.get_client()
            value = client.get(key)
            if value:
                try:
                    return json.loads(value)
                except json.JSONDecodeError:
                    return value
            return None
        except Exception as e:
            logger.error(f"Cache get error: {e}")
            return None
    
    async def delete(self, key: str) -> bool:
        """Delete a key from cache"""
        try:
            client = self.get_client()
            return client.delete(key) > 0
        except Exception as e:
            logger.error(f"Cache delete error: {e}")
            return False


# Global cache instance
cache_service = CacheService()