File size: 2,242 Bytes
4a45067
 
73f9fb2
 
f1fb766
4a45067
73f9fb2
 
 
 
 
 
f1fb766
 
 
73f9fb2
 
 
f1fb766
 
73f9fb2
4a45067
 
73f9fb2
f1fb766
73f9fb2
f1fb766
 
 
4a45067
73f9fb2
 
 
 
 
 
 
 
 
f1fb766
 
73f9fb2
4a45067
73f9fb2
 
 
f1fb766
73f9fb2
3f5b0f9
73f9fb2
 
 
3f5b0f9
f1fb766
 
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
# 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}")