0Pricing
Caching Strategies: Redis + CDN + Edge Computing · บทเรียน

โครงสร้างข้อมูลของรีดิสสำหรับแคช

สำรวจวิธีใช้โครงสร้างข้อมูลของรีดิส เช่น สตริง แฮช และเซตเรียงลำดับ ให้เกิดประสิทธิภาพในสถานการณ์การแคชรูปแบบต่าง ๆ

โครงสร้างข้อมูลของรีดิสสำหรับแคช เป็นบทเรียน Caching Strategies: Redis + CDN + Edge Computing ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Caching Strategies: Redis + CDN + Edge Computing และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Caching Strategies: Redis + CDN + Edge Computing มีบทเรียนทั้งหมด 4 บทเรียน

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

Redis Data Structures for Cache

Redis isn't just a simple key-value store! It offers a variety of powerful data structures, each optimized for different types of data and caching scenarios.

Understanding these structures is key to designing efficient and flexible caching solutions. You'll learn when to use strings, hashes, and sorted sets to store your application's data.

Strings for Basic Caching

The simplest Redis data type is a String. It's perfect for caching basic key-value pairs, like a user's session token, a page's HTML content, or a simple counter.

Think of it as a dictionary where keys map directly to a single value. It's fast and straightforward for common caching needs.

  • SET key value: Stores a string value.
  • GET key: Retrieves a string value.
  • DEL key: Removes a key and its value.

Caching User Session Data

Here's how you might cache a user's last login timestamp using a Redis string. Run this code to see it in action!

import redis
import time

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

def main():
    user_id = "user:123"
    last_login_key = f"{user_id}:last_login"
    current_time = int(time.time())

    # Cache the current login time
    r.set(last_login_key, current_time)
    print(f"Cached last login for {user_id}: {current_time}")

    # Retrieve the cached login time
    cached_login = r.get(last_login_key)
    print(f"Retrieved cached last login: {cached_login}")

    # Clean up (optional)
    # r.delete(last_login_key)

if __name__ == "__main__":
    main()

Hashes for Object Caching

When you need to cache structured data, like an entire user profile or product details, Hashes are ideal. They let you store multiple field-value pairs under a single key.

This is more efficient than using separate string keys for each attribute of an object, as it groups related data logically together.

  • HSET key field value [field value ...]: Sets multiple fields and values in a hash.
  • HGETALL key: Retrieves all fields and values from a hash.
  • HGET key field: Retrieves a specific field's value.

Caching Product Information

Let's cache details for a product, like its name, price, and stock count. Run this code to see how hashes store structured data.

import redis

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

def main():
    product_id = "product:456"
    
    # Cache product details as a Hash
    r.hset(product_id, mapping={
        "name": "Wireless Headphones",
        "price": "99.99",
        "stock": "500"
    })
    print(f"Cached product details for {product_id}")

    # Retrieve all product details
    product_details = r.hgetall(product_id)
    print(f"Retrieved product details: {product_details}")

    # Retrieve a specific field
    product_name = r.hget(product_id, "name")
    print(f"Retrieved product name: {product_name}")

    # Clean up (optional)
    # r.delete(product_id)

if __name__ == "__main__":
    main()

Sorted Sets: Ranked & Timed Data

Sorted Sets are unique because each member has an associated score, allowing Redis to keep the elements sorted. This is perfect for caching leaderboards, recently viewed items (by timestamp), or items ranked by popularity.

They combine the uniqueness of Sets with the ability to order elements. You can retrieve ranges of items by score or rank.

  • ZADD key score member [score member ...]: Adds members with scores.
  • ZRANGE key start stop [WITHSCORES]: Retrieves members by index (rank).
  • ZRANGEBYSCORE key min max [WITHSCORES]: Retrieves members by score range.

Caching a Game Leaderboard

Imagine caching a game's top scores. Sorted sets make this easy! The 'score' for each member determines its rank. Run the example.

import redis

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

def main():
    leaderboard_key = "game:leaderboard"

    # Add players and their scores to the leaderboard
    r.zadd(leaderboard_key, {"Alice": 1500, "Bob": 1200, "Charlie": 1800, "David": 1500})
    print("Added players to leaderboard.")

    # Retrieve the top 3 players (highest score first)
    # ZREVRANGE is used for descending order by score
    top_players = r.zrevrange(leaderboard_key, 0, 2, withscores=True)
    print("Top 3 players:")
    for player, score in top_players:
        print(f"- {player}: {int(score)}") # scores are float by default

    # Clean up (optional)
    # r.delete(leaderboard_key)

if __name__ == "__main__":
    main()

Essential: Cache Expiration (TTL)

For any cached data, setting an expiration time (Time To Live - TTL) is crucial. This prevents stale data and manages memory usage.

Redis automatically removes keys once their TTL expires, ensuring your cache stays fresh and doesn't grow indefinitely.

  • EXPIRE key seconds: Sets a TTL for an existing key.
  • SETEX key seconds value: Sets a key with a value and a TTL in one command.
  • TTL key: Checks remaining TTL.

When to Use Which Structure?

Choosing the right data structure depends on your caching needs:

  • Strings: For simple, atomic key-value pairs (e.g., individual values, counters, rendered HTML snippets).
  • Hashes: For caching entire objects or records with multiple fields (e.g., user profiles, product attributes).
  • Sorted Sets: For ordered lists, rankings, leaderboards, or time-series data where elements need scores for sorting.

Always consider how you'll access and manage the data.

Caching Scenario Challenge

You need to cache the following two types of data for a social media application:

  1. The current number of likes on a specific post.
  2. A list of the 10 most recent comments on that post, ordered by timestamp.

Which Redis data structures would be most appropriate for each, respectively?

Redis Data Structures Recap

Great job! You've explored the core Redis data structures and their applications in caching:

  • Strings for simple key-value pairs.
  • Hashes for structured objects.
  • Sorted Sets for ordered, scored lists.

You also learned the importance of TTL for managing cache freshness.

In the next lesson, we'll dive into basic Redis cache operations, putting these structures to practical use!

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

บทเรียน “โครงสร้างข้อมูลของรีดิสสำหรับแคช” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “โครงสร้างข้อมูลของรีดิสสำหรับแคช” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Caching Strategies: Redis + CDN + Edge Computing ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Caching Strategies: Redis + CDN + Edge Computing มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “โครงสร้างข้อมูลของรีดิสสำหรับแคช”

สำรวจวิธีใช้โครงสร้างข้อมูลของรีดิส เช่น สตริง แฮช และเซตเรียงลำดับ ให้เกิดประสิทธิภาพในสถานการณ์การแคชรูปแบบต่าง ๆ คุณปฏิบัติ Caching Strategies: Redis + CDN + Edge Computing ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Caching Strategies: Redis + CDN + Edge Computing หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Caching Strategies: Redis + CDN + Edge Computing บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “โครงสร้างข้อมูลของรีดิสสำหรับแคช” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Caching Strategies: Redis + CDN + Edge Computing นี้ได้ไหม

ได้ บทเรียน Caching Strategies: Redis + CDN + Edge Computing ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. บทนำสู่การแคชด้วยรีดิส
  2. โครงสร้างข้อมูลของรีดิสสำหรับแคช
  3. การดำเนินการแคชพื้นฐานในรีดิส
  4. TTL และการหมดอายุใน Redis
← กลับไปที่ Caching Strategies: Redis + CDN + Edge Computing