NestJS 如何使用 CacheModule 集成内存缓存(Memory)或 Redis 缓存?
解读
国内一线/二线互联网公司在面试 NestJS 岗位时,几乎都会追问“缓存怎么搭”。
面试官真正想确认的是:
- 你是否理解 NestJS 的 IoC 与动态模块注册机制;
- 能否根据环境(本地/测试/生产)无痛切换内存与 Redis,而不改业务代码;
- 是否掌握缓存雪崩、穿透、并发回源、序列化、TTL 等生产级细节;
- 能否把缓存与拦截器、装饰器、微服务配置中心结合,体现“企业级”思维。
回答时切忌只贴代码,要体现“可灰度、可观测、可回滚”的落地经验。
知识点
- CacheModule.register() 与 CacheModule.registerAsync() 的区别——后者支持注入 ConfigService,实现“配置中心驱动”。
- cache-manager 包内存存储(memory-cache)与 cache-manager-redis-store 的 store 接口差异。
- 自定义 CacheInterceptor 实现“可跳过缓存”装饰器 @SkipCache(),满足实时性接口。
- 使用 CACHE_MANAGER 令牌拿到 Cache 实例,手动做 compare-and-set、分布式锁。
- 在微服务场景下,Redis 缓存与 gRPC 拦截器结合,实现跨服务缓存一致性。
- 通过 cache-manager-redis-store@3 以上版本支持 Redis Cluster、哨兵、TLS,满足金融级要求。
- 利用 class-transformer 做缓存对象序列化,防止存取 Date、Map、BigInt 丢失类型。
- 缓存雪崩治理:在 ConfigService 里为不同 key 前缀设置随机 TTL(±10%),并配合互斥锁(Redlock)。
- 单元测试:使用 cache-manager-mock 替换 store,保证 CI 流水线不依赖 Redis。
- 可观测:在 APP_INTERCEPTOR 里埋点,把缓存命中率、耗时打到阿里云 SLS 或 Prometheus。
答案
一、最小可运行示例(本地内存)
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [
CacheModule.register({
ttl: 5, // 秒
max: 100, // 最大 key 数
}),
],
controllers: [AppController],
})
export class AppModule {}
在控制器里直接使用:
@Controller()
export class AppController {
constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}
@Get()
async hello(@Query('id') id: string) {
const key = `user_${id}`;
let data = await this.cache.get(key);
if (!data) {
data = await this.loadFromDb(id);
await this.cache.set(key, data, 300); // 5 分钟
}
return data;
}
}
二、生产级 Redis 方案(配置中心驱动,支持 Cluster、TLS、雪崩治理)
- 安装依赖
pnpm i cache-manager cache-manager-redis-store ioredis
- 配置中心(阿里云 ACM、Nacos、Apollo 均可)注入
export const cacheConfig = registerAs('cache', () => ({
store: 'redis',
host: process.env.REDIS_HOST,
port: +process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
db: +process.env.REDIS_DB || 0,
ttl: +process.env.CACHE_TTL || 600,
cluster: process.env.REDIS_CLUSTER === 'true',
nodes: process.env.REDIS_CLUSTER_NODES?.split(',') || [],
keyPrefix: process.env.APP_NAME + ':',
// 雪崩治理:随机抖动 10%
randomizeTtl: true,
}));
- 动态注册 CacheModule
import { CacheModule, Module, Global } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { cacheConfig } from './config';
@Global()
@Module({
imports: [
CacheModule.registerAsync({
imports: [ConfigModule.forFeature(cacheConfig)],
inject: [ConfigService],
useFactory: async (cfg: ConfigService) => {
const conf = cfg.get('cache');
return {
store: redisStore,
...conf,
ttl: conf.randomizeTtl ? conf.ttl + Math.floor(Math.random() * conf.ttl * 0.1) : conf.ttl,
};
},
}),
],
exports: [CacheModule],
})
export class RedisCacheModule {}
- 在 AppModule 里导入 RedisCacheModule 即可,业务代码零改动。
三、拦截器统一缓存(推荐)
@Injectable()
export class HttpCacheInterceptor extends CacheInterceptor {
protected trackBy(context: ExecutionContext): string {
const req = context.switchToHttp().getRequest();
return `http_${req.route?.path || req.url}_${JSON.stringify(req.query)}`;
}
}
在需要缓存的控制器上加 @UseInterceptors(HttpCacheInterceptor) 即可,TTL 通过 @CacheTTL(30) 细粒度控制。
四、自定义装饰器跳过缓存
export const SkipCache = () => SetMetadata('skip-cache', true);
在拦截器里读取该 metadata,命中则直接 return next.handle()。
五、单元测试(Jest)
const module: TestingModule = await Test.createTestingModule({
imports: [RedisCacheModule],
})
.overrideProvider(CACHE_MANAGER)
.useValue(createMockCache()) // 内存实现
.compile();
CI 无需 Redis 实例,流水线秒级通过。
拓展思考
- 多级缓存:本地 Caffeine + Redis,如何借助 nestjs-cacheable 做 L1/L2 同步?
- 缓存与事务:在 TypeORM 的 QueryRunner 中,事务提交成功后再删缓存,失败则回滚,如何封装 AOP?
- 缓存与灰度:利用配置中心给 20% 用户开启新缓存 key,观察命中率曲线,如何设计开关?
- 缓存与权限:JWT 解析后得到的角色不同,同一接口缓存 key 需要带角色维度,怎样避免 key 爆炸?
- 缓存与 Serverless:在阿里云函数计算中,Redis 长连接会被冻结,如何用 lazy connection + connection pool 解决冷启动?