Python中有哪些缓存实现方式?

中等Python

答题要点

from functools import lru_cache, cache
from cachetools import TTLCache, LRUCache
import redis

# 内存缓存(lru_cache)
@lru_cache(maxsize=128)
def expensive_computation(n):
    return sum(i**2 for i in range(n))

# Python 3.9+ 无限缓存
@cache
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# TTL缓存(过期)
ttl_cache = TTLCache(maxsize=100, ttl=300)

def get_user(user_id):
    if user_id in ttl_cache:
        return ttl_cache[user_id]
    user = fetch_from_db(user_id)
    ttl_cache[user_id] = user
    return user

# Redis缓存
r = redis.Redis()

def get_data(key):
    cached = r.get(key)
    if cached:
        return json.loads(cached)
    data = fetch_data(key)
    r.setex(key, 300, json.dumps(data))  # 5分钟过期
    return data

# 装饰器封装
def cached(ttl=300):
    def decorator(func):
        cache = {}
        @wraps(func)
        def wrapper(*args):
            if args in cache:
                value, timestamp = cache[args]
                if time.time() - timestamp < ttl:
                    return value
            result = func(*args)
            cache[args] = (result, time.time())
            return result
        return wrapper
    return decorator

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题