Redis 是最流行的内存数据库,合理的缓存策略能极大提升系统性能。

常见缓存模式

Cache-Aside(旁路缓存)

最常用的缓存模式,应用程序负责维护缓存:

python
def get_user(user_id):
    # 1. 先查缓存
    user = redis.get(f"user:{user_id}")
    if user:
        return json.loads(user)

    # 2. 缓存未命中,查数据库
    user = db.query("SELECT * FROM users WHERE id = %s", user_id)

    # 3. 写入缓存
    redis.setex(f"user:{user_id}", 3600, json.dumps(user))
    return user

Read-Through / Write-Through

缓存层自动同步数据库,应用程序只与缓存交互。

Write-Behind

先写缓存,异步写入数据库,适合写多读少场景。

缓存过期策略

bash
# 设置过期时间(秒)
SET key value EX 3600

# 设置过期时间(毫秒)
SET key value PX 60000

# 查看剩余时间
TTL key

过期 key 删除策略

策略 说明 优缺点
惰性删除 访问时检查过期 节省CPU,可能内存泄漏
定期删除 定期抽样删除 折中方案
LRU 淘汰最近最少使用 适合通用场景
LFU 淘汰使用频率最低 适合热点数据

缓存穿透

大量请求查询不存在的数据,绕过缓存直接打到数据库:

python
# 方案1:缓存空值
def get_user(user_id):
    user = redis.get(f"user:{user_id}")
    if user == "NULL":
        return None  # 缓存的空值
    if user:
        return json.loads(user)

    user = db.query("SELECT * FROM users WHERE id = %s", user_id)
    if not user:
        redis.setex(f"user:{user_id}", 60, "NULL")  # 缓存空值60秒
        return None

    redis.setex(f"user:{user_id}", 3600, json.dumps(user))
    return user

# 方案2:布隆过滤器
from pybloom_live import ScalableBloomFilter

bloom = ScalableBloomFilter()
# 启动时加载所有存在的 key
for id in db.query("SELECT id FROM users"):
    bloom.add(str(id))

def get_user_safe(user_id):
    if str(user_id) not in bloom:
        return None  # 布隆过滤器说不存在,直接返回
    return get_user(user_id)

缓存雪崩

大量缓存同时过期,导致数据库瞬时压力激增:

python
import random

def set_cache(key, value, base_ttl=3600):
    # 随机过期时间,避免同时失效
    ttl = base_ttl + random.randint(0, 300)
    redis.setex(key, ttl, json.dumps(value))

缓存击穿

热点 key 过期瞬间,大量请求打到数据库:

python
import threading

def get_hot_data(key):
    data = redis.get(key)
    if data:
        return json.loads(data)

    # 加锁,只让一个请求查数据库
    lock = redis.set(f"lock:{key}", "1", nx=True, ex=10)
    if lock:
        try:
            data = db.query_hot_data(key)
            redis.setex(key, 3600, json.dumps(data))
            return data
        finally:
            redis.delete(f"lock:{key}")
    else:
        # 等待后重试
        time.sleep(0.1)
        return get_hot_data(key)

分布式锁

python
import uuid

def distributed_lock(redis_conn, lock_name, timeout=10):
    identifier = str(uuid.uuid4())

    # 获取锁
    if redis_conn.set(lock_name, identifier, nx=True, ex=timeout):
        return identifier
    return None

def release_lock(redis_conn, lock_name, identifier):
    # Lua 脚本保证原子性
    script = """
    if redis.call("get", KEYS[1]) == ARGV[1] then
        return redis.call("del", KEYS[1])
    else
        return 0
    end
    """
    redis_conn.eval(script, 1, lock_name, identifier)

总结

Redis 缓存策略的选择需要根据业务场景来定。Cache-Aside 适合大多数场景;缓存穿透用布隆过滤器或空值缓存;雪崩用随机过期时间;击穿用互斥锁。合理使用这些策略能让系统性能提升数倍。