0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

กลยุทธ์การแคชด้วย Redis

ผสานรวม Redis เพื่อแคชการตอบกลับของ API และข้อมูลที่มีการเข้าถึงบ่อย เพื่อเพิ่มประสิทธิภาพ

กลยุทธ์การแคชด้วย Redis เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Caching Matters

Imagine your app fetching the same data repeatedly from a slow database or an external service. This slows things down for your users!

Caching is the process of storing frequently accessed data in a faster, temporary location. It's like having a quick-access shortcut for information.

  • Speeds up response times: Users get data faster.
  • Reduces load: Less strain on your databases and APIs.
  • Improves performance: Your application feels snappier and can handle more users.

Meet Redis: A Fast Cache

Redis (Remote Dictionary Server) is an open-source, in-memory data store. Being in-memory means it keeps data in RAM, making it incredibly fast!

It's often called a 'data structure store' because it supports various data types like strings, hashes, lists, and sets, not just simple key-value pairs.

For caching in FastAPI, Redis acts like a lightning-fast key-value store, perfect for storing API responses.

How Redis Caching Works

When a FastAPI endpoint needs data, it first checks Redis.

  • Cache Hit: If the data is found in Redis, it's returned immediately. This is super fast!
  • Cache Miss: If the data isn't in Redis, FastAPI fetches it from the original source (e.g., a database). Before returning it, a copy is stored in Redis for future requests.

This strategy ensures that subsequent requests for the same data benefit from the speed of the cache.

Connecting FastAPI to Redis

To use Redis with Python, we'll leverage the redis-py library (specifically its asynchronous version, redis.asyncio). First, install it: pip install redis.

Then, you establish a connection to your Redis server. You can inject this connection as a dependency in your FastAPI application.

Here's how to create a basic asynchronous Redis client and test the connection:

import redis.asyncio as redis
import asyncio

async def connect_to_redis():
    # Connect to Redis server (default host/port)
    r = redis.Redis(host='localhost', port=6377, db=0, decode_responses=True)
    try:
        # Ping to check connection
        await r.ping()
        print("Successfully connected to Redis!")
    except redis.exceptions.ConnectionError as e:
        print(f"Could not connect to Redis: {e}")
    finally:
        # Close the connection when done
        await r.close()

if __name__ == "__main__":
    # Run the async function
    asyncio.run(connect_to_redis())

Basic SET and GET Operations

Redis is a key-value store. You use SET to store a value associated with a unique key, and GET to retrieve it.

The decode_responses=True parameter in the client setup ensures that retrieved bytes are automatically decoded into Python strings.

Let's see a simple example of storing and fetching a string:

import redis.asyncio as redis
import asyncio

async def basic_cache_example():
    r = redis.Redis(host='localhost', port=6377, db=0, decode_responses=True)
    key = "app:greeting"
    value = "Hello from your Redis cache!"

    # Store a value with a key
    await r.set(key, value)
    print(f"Set key '{key}' with value: '{value}'")

    # Retrieve the value using its key
    cached_value = await r.get(key)
    print(f"Retrieved value for '{key}': '{cached_value}'")

    await r.close()

if __name__ == "__main__":
    asyncio.run(basic_cache_example())

Caching Complex Data (JSON)

API responses are typically complex data structures, like Python dictionaries, which are then serialized to JSON. Redis stores string values.

To cache a dictionary, we first convert it to a JSON string using Python's built-in json module. When retrieving, we parse the JSON string back into a dictionary.

This allows us to cache rich data objects efficiently.

import redis.asyncio as redis
import asyncio
import json

async def cache_json_object_example():
    r = redis.Redis(host='localhost', port=6377, db=0, decode_responses=True)
    
    user_id = "user_456"
    user_profile = {"name": "Alice", "email": "alice@example.com", "age": 30}
    
    # Convert Python dict to JSON string
    json_profile = json.dumps(user_profile)
    
    # Store the JSON string in Redis
    await r.set(f"user:{user_id}", json_profile)
    print(f"Cached user profile for {user_id}")
    
    # Retrieve the JSON string from Redis
    cached_json = await r.get(f"user:{user_id}")
    if cached_json:
        # Convert JSON string back to Python dict
        retrieved_profile = json.loads(cached_json)
        print(f"Retrieved user name: {retrieved_profile['name']}")
    
    await r.close()

if __name__ == "__main__":
    asyncio.run(cache_json_object_example())

Managing Cache Expiry (TTL)

Cached data can become 'stale' if the original data in the database changes. Serving stale data can be worse than no cache at all!

Time-To-Live (TTL) is a crucial concept. It's a duration (in seconds) after which a cached item is automatically removed from Redis.

Using TTL ensures your cache stays fresh, preventing you from serving outdated information without manual intervention.

Caching with TTL in FastAPI

When using the SET command in Redis, you can add an ex parameter to specify the expiry time in seconds (or px for milliseconds).

This example demonstrates a FastAPI endpoint that caches an item for 60 seconds. If you request the same item within 60 seconds, it's served from the cache; otherwise, it's fetched from the (simulated) database again.

from fastapi import FastAPI, Depends
import redis.asyncio as redis
import asyncio
import json

app = FastAPI()

# Dependency to get a Redis client instance
async def get_redis_client():
    r = redis.Redis(host='localhost', port=6377, db=0, decode_responses=True)
    try:
        yield r # Provide the client
    finally:
        await r.close() # Ensure client is closed after request

@app.get("/products/{product_id}")
async def read_product(product_id: str, redis_client: redis.Redis = Depends(get_redis_client)):
    cache_key = f"product:{product_id}"
    
    # 1. Try to get data from cache
    cached_data = await redis_client.get(cache_key)
    if cached_data:
        print(f"Cache hit for {product_id}!")
        return json.loads(cached_data)
    
    # 2. If not in cache, simulate fetching from database
    print(f"Cache miss for {product_id}. Fetching from DB...")
    await asyncio.sleep(1) # Simulate I/O delay for DB call
    product_data = {"id": product_id, "name": f"Product {product_id}", "price": 99.99}
    
    # 3. Store in cache with 60-second TTL
    await redis_client.set(cache_key, json.dumps(product_data), ex=60)
    
    return product_data

# To run this example:
# 1. Ensure a Redis server is running (e.g., `redis-server` in your terminal).
# 2. Save this code as `main.py`.
# 3. Run Uvicorn: `uvicorn main:app --reload`.
# 4. Access in your browser: `http://127.0.0.1:8000/products/123`.
#    Refresh the page to see 'Cache hit' messages after the first request.

Cache Invalidation & Considerations

While TTL handles automatic expiry, sometimes you need to manually remove an item from the cache if its source data changes before the TTL expires.

This is called cache invalidation. For example, if a user updates their profile, you'd explicitly delete their old profile data from the cache using redis_client.delete(key).

Considerations for caching:

  • Data Volatility: Don't cache highly dynamic data that changes every second.
  • Memory Usage: Redis stores data in RAM, so be mindful of your server's memory capacity.
  • Consistency: Balance between freshness and performance.

Quick Check

You've learned about Redis and how to implement basic caching strategies. Let's test your understanding of its benefits.

Recap: Caching for Performance

Excellent work! You've successfully explored how Redis can significantly boost your FastAPI application's performance and scalability.

Here's a quick recap of what we covered:

  • What is Caching: Storing data temporarily for faster access.
  • Introducing Redis: A fast, in-memory key-value store.
  • Connecting to Redis: Using redis.asyncio for client connection.
  • Basic Operations: SET and GET for caching strings and JSON.
  • Time-To-Live (TTL): Automatically expiring cached data with the ex parameter.
  • Invalidation: Manually removing stale data.

Next, you might explore more advanced Redis features like Pub/Sub for real-time updates or using Redis Hashes for more structured cached data.

คำถามที่พบบ่อย

บทเรียน “กลยุทธ์การแคชด้วย Redis” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “กลยุทธ์การแคชด้วย Redis” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “กลยุทธ์การแคชด้วย Redis”

ผสานรวม Redis เพื่อแคชการตอบกลับของ API และข้อมูลที่มีการเข้าถึงบ่อย เพื่อเพิ่มประสิทธิภาพ คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “กลยุทธ์การแคชด้วย Redis” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. กลยุทธ์การแคชด้วย Redis
  2. การเข้าถึงฐานข้อมูลแบบอะซิงโครนัส
  3. การกระจายภาระและการตรวจสอบ
  4. งานเบื้องหลังและคิวงาน
← กลับไปที่ FastAPI Backend Development Bootcamp