monitor_eviction.py 2.9 KB
#!/usr/bin/env python3
"""
Real-time monitoring of Redis cache eviction events

Continuously monitor evicted_keys statistics and warn when new evictions occur
"""

import redis
import time
import sys
from pathlib import Path
from datetime import datetime

# 添加项目路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from config.env_config import REDIS_CONFIG

def get_redis_client():
    """Get Redis client"""
    return redis.Redis(
        host=REDIS_CONFIG.get('host', 'localhost'),
        port=REDIS_CONFIG.get('port', 6479),
        password=REDIS_CONFIG.get('password'),
        decode_responses=True,
        socket_timeout=5,
        socket_connect_timeout=5,
    )

def monitor_eviction(interval=5):
    """Continuously monitor eviction events"""
    print("=" * 60)
    print("Redis Cache Eviction Real-time Monitoring")
    print("=" * 60)
    print(f"Monitoring interval: {interval} seconds")
    print("Press Ctrl+C to stop monitoring")
    print("=" * 60)
    print()
    
    try:
        client = get_redis_client()
        client.ping()
    except Exception as e:
        print(f"❌ Redis connection failed: {e}")
        return
    
    last_evicted = 0
    
    try:
        while True:
            info = client.info('stats')
            current_evicted = info.get('evicted_keys', 0)
            
            if current_evicted > last_evicted:
                new_evictions = current_evicted - last_evicted
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                print(f"[{timestamp}] ⚠️  Detected {new_evictions} new eviction events!")
                print(f"    Total evictions: {current_evicted:,}")
                
                # 检查内存使用情况
                mem_info = client.info('memory')
                maxmemory = mem_info.get('maxmemory', 0)
                used_memory = mem_info.get('used_memory', 0)
                if maxmemory > 0:
                    usage_percent = (used_memory / maxmemory) * 100
                    print(f"    Current memory usage: {usage_percent:.2f}%")
                
                last_evicted = current_evicted
            else:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                print(f"[{timestamp}] ✅ No new eviction events (Total: {current_evicted:,})")
            
            time.sleep(interval)
            
    except KeyboardInterrupt:
        print("\n\nMonitoring stopped")
    except Exception as e:
        print(f"\n❌ Monitoring error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Real-time monitoring of Redis cache eviction events')
    parser.add_argument('--interval', type=int, default=5, help='Monitoring interval in seconds (default: 5)')
    args = parser.parse_args()
    
    monitor_eviction(interval=args.interval)