|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Example demonstrating the Redis core for cachier. |
| 4 | +
|
| 5 | +This example shows how to use cachier with Redis as the backend for |
| 6 | +high-performance caching. |
| 7 | +
|
| 8 | +Requirements: |
| 9 | + pip install redis cachier |
| 10 | +""" |
| 11 | + |
| 12 | +import time |
| 13 | +from datetime import timedelta |
| 14 | + |
| 15 | +try: |
| 16 | + import redis |
| 17 | + from cachier import cachier |
| 18 | +except ImportError as e: |
| 19 | + print(f"Missing required package: {e}") |
| 20 | + print("Install with: pip install redis cachier") |
| 21 | + exit(1) |
| 22 | + |
| 23 | + |
| 24 | +def setup_redis_client(): |
| 25 | + """Set up a Redis client for caching.""" |
| 26 | + try: |
| 27 | + # Connect to Redis (adjust host/port as needed) |
| 28 | + client = redis.Redis( |
| 29 | + host="localhost", |
| 30 | + port=6379, |
| 31 | + db=0, |
| 32 | + decode_responses=False, # Important: keep as bytes for pickle |
| 33 | + ) |
| 34 | + # Test connection |
| 35 | + client.ping() |
| 36 | + print("✓ Connected to Redis successfully") |
| 37 | + return client |
| 38 | + except redis.ConnectionError: |
| 39 | + print("✗ Could not connect to Redis") |
| 40 | + print("Make sure Redis is running on localhost:6379") |
| 41 | + print("Or install and start Redis with: docker run -p 6379:6379 redis") |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def expensive_calculation(n): |
| 46 | + """Simulate an expensive calculation.""" |
| 47 | + print(f" Computing expensive_calculation({n})...") |
| 48 | + time.sleep(2) # Simulate work |
| 49 | + return n * n + 42 |
| 50 | + |
| 51 | + |
| 52 | +def demo_basic_caching(): |
| 53 | + """Demonstrate basic Redis caching.""" |
| 54 | + print("\n=== Basic Redis Caching ===") |
| 55 | + |
| 56 | + @cachier(backend="redis", redis_client=setup_redis_client()) |
| 57 | + def cached_calculation(n): |
| 58 | + return expensive_calculation(n) |
| 59 | + |
| 60 | + # First call - should be slow |
| 61 | + start = time.time() |
| 62 | + result1 = cached_calculation(5) |
| 63 | + time1 = time.time() - start |
| 64 | + print(f"First call: {result1} (took {time1:.2f}s)") |
| 65 | + |
| 66 | + # Second call - should be fast (cached) |
| 67 | + start = time.time() |
| 68 | + result2 = cached_calculation(5) |
| 69 | + time2 = time.time() - start |
| 70 | + print(f"Second call: {result2} (took {time2:.2f}s)") |
| 71 | + |
| 72 | + assert result1 == result2 |
| 73 | + assert time2 < time1 |
| 74 | + print("✓ Caching working correctly!") |
| 75 | + |
| 76 | + |
| 77 | +def demo_stale_after(): |
| 78 | + """Demonstrate stale_after functionality with Redis.""" |
| 79 | + print("\n=== Stale After Demo ===") |
| 80 | + |
| 81 | + @cachier( |
| 82 | + backend="redis", |
| 83 | + redis_client=setup_redis_client(), |
| 84 | + stale_after=timedelta(seconds=3), |
| 85 | + ) |
| 86 | + def time_sensitive_calculation(n): |
| 87 | + return expensive_calculation(n) |
| 88 | + |
| 89 | + # First call |
| 90 | + result1 = time_sensitive_calculation(10) |
| 91 | + print(f"First call: {result1}") |
| 92 | + |
| 93 | + # Second call within 3 seconds - should use cache |
| 94 | + result2 = time_sensitive_calculation(10) |
| 95 | + print(f"Second call (within 3s): {result2}") |
| 96 | + assert result1 == result2 |
| 97 | + |
| 98 | + # Wait for cache to become stale |
| 99 | + print("Waiting 4 seconds for cache to become stale...") |
| 100 | + time.sleep(4) |
| 101 | + |
| 102 | + # Third call after 4 seconds - should recalculate |
| 103 | + result3 = time_sensitive_calculation(10) |
| 104 | + print(f"Third call (after 4s): {result3}") |
| 105 | + assert result3 != result1 |
| 106 | + print("✓ Stale after working correctly!") |
| 107 | + |
| 108 | + |
| 109 | +def demo_callable_client(): |
| 110 | + """Demonstrate using a callable Redis client.""" |
| 111 | + print("\n=== Callable Client Demo ===") |
| 112 | + |
| 113 | + def get_redis_client(): |
| 114 | + """Factory function for Redis client.""" |
| 115 | + return redis.Redis( |
| 116 | + host="localhost", port=6379, db=0, decode_responses=False |
| 117 | + ) |
| 118 | + |
| 119 | + @cachier(backend="redis", redis_client=get_redis_client) |
| 120 | + def cached_with_callable(n): |
| 121 | + return expensive_calculation(n) |
| 122 | + |
| 123 | + result1 = cached_with_callable(15) |
| 124 | + result2 = cached_with_callable(15) |
| 125 | + assert result1 == result2 |
| 126 | + print(f"Callable client result: {result1}") |
| 127 | + print("✓ Callable client working correctly!") |
| 128 | + |
| 129 | + |
| 130 | +def demo_cache_management(): |
| 131 | + """Demonstrate cache management functions.""" |
| 132 | + print("\n=== Cache Management Demo ===") |
| 133 | + |
| 134 | + @cachier(backend="redis", redis_client=setup_redis_client()) |
| 135 | + def managed_calculation(n): |
| 136 | + return expensive_calculation(n) |
| 137 | + |
| 138 | + # Cache some values |
| 139 | + managed_calculation(20) |
| 140 | + managed_calculation(21) |
| 141 | + |
| 142 | + # Clear the cache |
| 143 | + managed_calculation.clear_cache() |
| 144 | + print("✓ Cache cleared successfully!") |
| 145 | + |
| 146 | + # Verify cache is empty |
| 147 | + start = time.time() |
| 148 | + result = managed_calculation(20) # Should be slow again |
| 149 | + time_taken = time.time() - start |
| 150 | + print(f"After clearing cache: {result} (took {time_taken:.2f}s)") |
| 151 | + |
| 152 | + |
| 153 | +def main(): |
| 154 | + """Run all Redis core demonstrations.""" |
| 155 | + print("Cachier Redis Core Demo") |
| 156 | + print("=" * 50) |
| 157 | + |
| 158 | + # Check if Redis is available |
| 159 | + client = setup_redis_client() |
| 160 | + if client is None: |
| 161 | + return |
| 162 | + |
| 163 | + try: |
| 164 | + demo_basic_caching() |
| 165 | + demo_stale_after() |
| 166 | + demo_callable_client() |
| 167 | + demo_cache_management() |
| 168 | + |
| 169 | + print("\n" + "=" * 50) |
| 170 | + print("✓ All Redis core demonstrations completed successfully!") |
| 171 | + print("\nKey benefits of Redis core:") |
| 172 | + print("- High-performance in-memory caching") |
| 173 | + print("- Cross-process and cross-machine caching") |
| 174 | + print("- Optional persistence with Redis configuration") |
| 175 | + print("- Built-in expiration and eviction policies") |
| 176 | + |
| 177 | + except Exception as e: |
| 178 | + print(f"\n✗ Demo failed with error: {e}") |
| 179 | + finally: |
| 180 | + # Clean up |
| 181 | + if client: |
| 182 | + client.close() |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + main() |
0 commit comments