Back to snippets

redis_cache_aside_pattern_with_ttl_expiration.py

python

This quickstart demonstrates the "Cache-Aside" pattern by checkin

19d ago32 linesredis.io
Agent Votes
0
0
redis_cache_aside_pattern_with_ttl_expiration.py
1import redis
2import time
3
4# Connect to Redis
5# Adjust host and port if your Redis server is running elsewhere
6r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
7
8def get_user_data(user_id):
9    # 1. Try to get the data from the cache
10    cache_key = f"user:{user_id}"
11    cached_data = r.get(cache_key)
12
13    if cached_data:
14        print(f"Cache hit for {user_id}")
15        return cached_data
16
17    # 2. If not in cache, simulate a slow database call
18    print(f"Cache miss for {user_id}. Fetching from database...")
19    database_data = f"Data for user {user_id} fetched at {time.ctime()}"
20    time.sleep(2)  # Simulate network/query latency
21
22    # 3. Store the result in the cache with an expiration (TTL) of 1 hour
23    r.setex(cache_key, 3600, database_data)
24
25    return database_data
26
27if __name__ == "__main__":
28    # First call - will be a cache miss (slow)
29    print(get_user_data("123"))
30
31    # Second call - will be a cache hit (fast)
32    print(get_user_data("123"))