# modules/server_cache.py import time import redis import json import logging class RedisServerStatusCache: def __init__(self, host='localhost', port=6379, db=0, default_ttl=300): try: self.redis = redis.StrictRedis(host=host, port=port, db=db, decode_responses=True) # Test connection self.redis.ping() self.use_redis = True logging.info("Connected to Redis cache") except (redis.ConnectionError, redis.TimeoutError) as e: # Fallback to in-memory cache if Redis is not available self.redis = None self.fallback_cache = {} self.use_redis = False logging.warning(f"Redis not available, using in-memory cache: {e}") self.default_ttl = default_ttl def get(self, server_key): try: if self.use_redis and self.redis: status = self.redis.get(f"server_status:{server_key}") if status is not None: return json.loads(status) return None else: # Fallback to in-memory cache entry = self.fallback_cache.get(server_key) if entry: timestamp, status = entry if time.time() - timestamp < self.default_ttl: return status else: del self.fallback_cache[server_key] return None except Exception as e: logging.error(f"Cache get error: {e}") return None def set(self, server_key, status, ttl=None): try: ttl = ttl or self.default_ttl if self.use_redis and self.redis: self.redis.setex(f"server_status:{server_key}", ttl, json.dumps(status)) logging.debug(f"Cached status {status} for {server_key} in Redis (TTL: {ttl}s)") else: # Fallback to in-memory cache self.fallback_cache[server_key] = (time.time(), status) logging.debug(f"Cached status {status} for {server_key} in memory (TTL: {ttl}s)") except Exception as e: logging.error(f"Cache set error: {e}")