File size: 4,138 Bytes
2eef5d6 | 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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | """
Redis caching module with graceful fallback to in-memory dict when Redis is unavailable.
Usage:
from cache import cache_get, cache_set, cache_delete, cache_clear
cache_set("products:list", products, ttl=300)
products = cache_get("products:list")
"""
import os
import json
import time
import logging
from typing import Any, Optional
log = logging.getLogger(__name__)
REDIS_URL = os.environ.get("REDIS_URL", "")
_redis_client = None
_memory_cache: dict[str, tuple[Any, float]] = {}
def _get_redis():
"""Lazy-initialize Redis client. Returns None if unavailable."""
global _redis_client
if _redis_client is not None:
return _redis_client
if not REDIS_URL:
log.debug("No REDIS_URL — using in-memory cache")
return None
try:
import redis
_redis_client = redis.from_url(REDIS_URL, decode_responses=True, socket_timeout=2)
_redis_client.ping()
log.info("Redis connected (%s)", REDIS_URL.split("@")[-1] if "@" in REDIS_URL else REDIS_URL)
return _redis_client
except ImportError:
log.warning("redis-py not installed — using in-memory cache")
return None
except Exception as e:
log.warning("Redis unavailable: %s — using in-memory cache", e)
_redis_client = None
return None
def cache_get(key: str) -> Optional[Any]:
"""Get value from cache. Returns None if not found."""
# Try Redis first
r = _get_redis()
if r is not None:
try:
val = r.get(key)
if val is not None:
return json.loads(val)
return None
except Exception:
pass
# Fallback to in-memory cache
entry = _memory_cache.get(key)
if entry is None:
return None
value, expires = entry
if expires and time.time() > expires:
del _memory_cache[key]
return None
return value
def cache_set(key: str, value: Any, ttl: int = 300) -> None:
"""Set value in cache with TTL in seconds (default 5 min)."""
serialized = json.dumps(value, default=str)
# Try Redis
r = _get_redis()
if r is not None:
try:
r.setex(key, ttl, serialized)
return
except Exception:
pass
# Fallback to in-memory cache
expires = time.time() + ttl if ttl > 0 else 0
_memory_cache[key] = (value, expires)
def cache_delete(*keys: str) -> None:
"""Delete keys from cache."""
r = _get_redis()
if r is not None:
try:
r.delete(*keys)
except Exception:
pass
for k in keys:
_memory_cache.pop(k, None)
def cache_clear(pattern: str = "*") -> None:
"""Clear cache entries matching pattern."""
r = _get_redis()
if r is not None:
try:
cursor = 0
while True:
cursor, keys = r.scan(cursor, match=pattern, count=100)
if keys:
r.delete(*keys)
if cursor == 0:
break
except Exception:
pass
if pattern == "*":
_memory_cache.clear()
else:
import fnmatch
to_delete = [k for k in _memory_cache if fnmatch.fnmatch(k, pattern)]
for k in to_delete:
del _memory_cache[k]
def cache_stats() -> dict:
"""Return cache statistics."""
r = _get_redis()
redis_ok = r is not None
redis_info = {}
if redis_ok:
try:
info = r.info("memory")
redis_info = {
"used_memory_human": info.get("used_memory_human", "N/A"),
"connected_clients": r.info("clients").get("connected_clients", 0),
}
except Exception:
pass
return {
"backend": "redis" if redis_ok else "memory",
"redis": redis_info,
"memory_entries": len(_memory_cache),
}
def close_cache():
"""Close Redis connection."""
global _redis_client
if _redis_client is not None:
try:
_redis_client.close()
except Exception:
pass
_redis_client = None
|