Redis 缓存常见问题与解决方案

识别缓存穿透、击穿与雪崩,并在 Redis 不可用时保护核心业务。

🎯 引言

学完本文,你能减少不存在记录和热点记录带来的重复查询,并在 Redis 故障时让公开资料查询继续访问数据库。

本篇使用 Node.js 22.9.0、redis 5.9.0、mysql2 3.11.5、Redis 7.4.2,沿用上一篇的 MySQL 环境。下面的保护版使用 course:protected:*,与基础缓存实验分开。


🧱 缓存穿透与空值缓存

缓存穿透指请求越过缓存,反复查询数据源中也不存在的数据。如果程序只缓存存在的记录,那么“没有记录”这个结果每次都需要重新查数据库才能确认。

空值缓存是把“已经查过,但没有记录”也短暂保存下来,下次查询相同内容时直接返回空结果。

应用场景:用户详情等按编号查询的功能,经常收到不存在的编号时可以使用。空值缓存只对重复查询的编号有效,还需要校验输入并限制异常请求频率。

新建 read-through.mjs,先判断缓存内容是否可用:

read-through.mjs
function decodeUser(raw) {
    if (raw === null) return { hit: false };
    try {
        const value = JSON.parse(raw);
        if (value === null || (Number.isInteger(value.id) && typeof value.name === 'string')) {
            return { hit: true, value };
        }
    } catch {
        // 损坏的 JSON 按未命中处理。
    }
    return { hit: false };
}

Redis 返回的 null 表示键不存在;JSON 文本 "null" 表示之前查过但没有记录。损坏数据或字段不符时重新查询,避免把错误内容当成资料返回。

再实现读取流程:

read-through.mjs
export async function readThrough(cache, findUser, id, ttl = 60) {
    const key = `course:protected:user:${id}`;
    const cached = decodeUser(await cache.get(key));
    if (cached.hit) return cached.value;
    const user = await findUser(id);
    await cache.set(key, JSON.stringify(user), { EX: user === null ? 10 : ttl });
    return user;
}

cache 接收 Redis 客户端,findUser 接收数据库查询函数,便于后面替换缓存的故障处理方式。不存在的用户只保存 10 秒,正常资料使用传入的 ttl。


🛠 缓存击穿与请求合并

缓存击穿是一个访问量较大的 Key 失效后,大量请求同时查询它的数据源。这些请求在新副本写回之前都看到缓存缺失,因此一次失效可能引起很多次相同查询。

请求合并让同一 Key 的并发读取共用一次正在执行的查询,查询完成后把结果交给所有等待者。

应用场景:热门资料、热点内容在缓存到期时被集中访问。下面使用一个 Node.js 进程内共享的 Promise 演示合并。

新建 single-flight.mjs,模块中的 Map 保存正在执行的查询:

single-flight.mjs
const pending = new Map();

export async function runOnce(key, load) {
    if (pending.has(key)) return pending.get(key);
    const task = Promise.resolve().then(load);
    pending.set(key, task);
    try {
        return await task;
    } finally {
        pending.delete(key);
    }
}

查询成功或失败都会清理 Map,防止把一个失败 Promise 长期复用。它只协调当前进程,多个服务实例仍可能各自回源。

新建 protection-demo.mjs,准备验证:

protection-demo.mjs
import { redis } from './redis.mjs';
import { pool } from './db.mjs';
import { findUser, metrics } from './user-repository.mjs';
import { readThrough } from './read-through.mjs';
import { runOnce } from './single-flight.mjs';

await redis.connect();
await redis.del('course:protected:user:1');

同时发起 5 次查询:

protection-demo.mjs
const users = await Promise.all(Array.from({ length: 5 }, () =>
    runOnce('user:1', () => readThrough(redis, findUser, 1))
));
console.log(users.length, metrics.sourceReads);

新进程中输出 5 1:5 个调用拿到结果,数据库只读取一次。正常请求也必须经过同一个 runOnce,只在测试中包裹不能保护真实接口。


🧰 缓存雪崩与过期时间分散

缓存雪崩是大范围缓存同时无法提供结果,导致大量查询集中回到数据源。它可能由一批 Key 同时过期引起,也可能由 Redis 整体不可用引起;与击穿集中在一个热门 Key 不同,雪崩影响很多数据。

应用场景:批量预热或导入缓存时,可以为过期时间增加小范围随机值,让它们分散到期。Redis 整体故障则需要配合降级和数据库访问量限制。

在调用读取函数时给正常资料的 TTL 加一点随机变化:

protection-demo.mjs
await redis.del('course:protected:user:1');
const ttl = 60 + Math.floor(Math.random() * 10);
console.log(await readThrough(redis, findUser, 1, ttl));
console.log(await redis.ttl('course:protected:user:1'));

先删除实验键,确保这次会重新写入缓存;返回用户资料后,TTL 应接近生成的 60 到 69 秒。批量写入时,每个键分别生成随机值,使到期时间错开。

Redis 故障时的处理见下一节。


💡 Redis 不可用时的降级处理

降级是在部分依赖不可用时,改用仍能完成核心功能的处理方式。缓存是副本时,读取失败可以改查数据源,写入副本失败也不必丢弃已经查到的结果。数据源本身失败则不能伪装成正常结果。

应用场景:Redis 短暂不可用时,公开资料查询可以继续访问数据库,但要限制并发查询数量和等待时间,超出容量时返回繁忙响应。

先在 cache-access.mjs 中为单次缓存操作设置等待期限:

cache-access.mjs
import { redis } from './redis.mjs';

async function withinDeadline(operation) {
    const controller = new AbortController();
    let timer;
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => {
            reject(new Error('缓存操作等待超时'));
            controller.abort();
        }, 200);
    });
    try {
        const client = redis.withCommandOptions({ abortSignal: controller.signal });
        return await Promise.race([operation(client), timeout]);
    } finally {
        clearTimeout(timer);
    }
}

200 毫秒是练习预算,应按实际网络调整。取消信号用于尝试移除尚未发出的命令。

接着只在缓存操作外围处理失败:

cache-access.mjs
async function attempt(operation) {
    try {
        if (!redis.isReady) throw new Error('Redis 尚未就绪');
        return await withinDeadline(operation);
    } catch (error) {
        console.warn('缓存暂不可用:', error.message);
        return null;
    }
}

isReady 表示当前可以执行命令,但检查之后仍可能断线,所以保留调用处的捕获。实际服务应聚合错误日志,避免持续故障时每次请求都输出大量重复信息。

导出与前面读取函数匹配的接口:

cache-access.mjs
export const safeCache = {
    get: key => attempt(client => client.get(key)),
    set: (key, value, options) => attempt(client => client.set(key, value, options)),
};

在 protection-demo.mjs 继续追加。主动关闭本脚本的 Redis 连接,验证能否继续查询数据库:

protection-demo.mjs
import { safeCache } from './cache-access.mjs';

await redis.close();
console.log(await readThrough(safeCache, findUser, 1));
await pool.end();

这里关闭的是客户端连接,不会停止 Redis 服务。缓存读写会记录不可用提示,MySQL 正常时仍返回用户资料。运行:

node --env-file=.env protection-demo.mjs

真实服务如果在启动时就无法连接,也必须明确选择“启动失败”或“带降级能力启动”,不能只处理启动后的断线。

上述降级适用于可重建的缓存副本。Session 或限流记录不可用时,不能因忽略 Redis 错误而直接放行。

❓ 知识问答

Q1:空值缓存会不会阻止新用户被查到?

可能短暂阻止,因此空值期限通常较短,创建成功还要使对应空值键失效。

Q2:请求合并可以限制不同用户的查询总量吗?

不能。同键合并只减少相同查询,不同键仍可同时回源,需要额外的并发上限。

Q3:只用 Promise.race 就能停止 Redis 命令吗?

不能。它只决定调用方等待哪个结果;取消信号也无法撤销已经在服务端执行的操作。


🧪 小练习

选择确认不存在的用户编号,连续查两次,验证数据库只读一次;再传入一个会抛错的查询函数,确认数据库错误不会被当成空值缓存。

// 请在这里编写代码

🎉 恭喜你已经掌握空值缓存、请求合并与缓存故障处理啦!