Nâng CaoNestJS iconNestJS

Caching với Redis trong NestJS — CacheModule, TTL strategy và cache invalidation?

Setup với @nestjs/cache-manager và Redis:

typescript
CacheModule.registerAsync({
  isGlobal: true,
  useFactory: async (config: ConfigService) => ({
    store: await redisStore({ socket: { host: config.get('REDIS_HOST'), port: 6379 } }),
    ttl: 60 * 1000,  // 60 giây default
  }),
  inject: [ConfigService],
})

Automatic caching với interceptor:

typescript
@UseInterceptors(CacheInterceptor)
@CacheTTL(300)  // NestJS decorator dùng SECONDS (300s = 5 phút)
@Get('products')
async getProducts() { ... }

Manual caching (more control):

typescript
constructor(@Inject(CACHE_MANAGER) private cache: Cache) {}

async getProduct(id: number) {
  const cached = await this.cache.get<Product>(`product:${id}`);
  if (cached) return cached;

  const product = await this.repo.findOne({ where: { id } });
  await this.cache.set(`product:${id}`, product, 300000);  // cache-manager v5 dùng MILLISECONDS
  return product;
}

async updateProduct(id: number, dto: UpdateProductDto) {
  const product = await this.repo.save({ id, ...dto });
  await this.cache.del(`product:${id}`);  // Invalidate
  return product;
}

Cache-aside pattern: luôn invalidate khi write, set TTL ngắn hơn thực tế cần để tránh stale data quá lâu.

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

Mở danh sách NestJS