Nâng CaoPython iconPython

Caching strategy trong Python API — Redis pattern?

Cache-aside pattern: application kiểm tra cache trước, nếu miss thì query DB và populate cache.

python
import json
from functools import wraps

def cache(key_prefix: str, ttl: int = 300):
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            key = f"{key_prefix}:{args}:{kwargs}"
            cached = await redis.get(key)
            if cached:
                return json.loads(cached)

            result = await func(*args, **kwargs)
            await redis.setex(key, ttl, json.dumps(result))
            return result
        return wrapper
    return decorator

@cache("products", ttl=60)
async def get_products():
    return await db.query_products()

Invalidation: redis.delete(key) khi data thay đổi.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python