पाठ 22 / 34
Caching
CacheModule, CacheInterceptor और TTLs के साथ in-memory या Redis caching से responses तेज़ करें।
Cache decorator
GET responses cache करने के लिए CacheInterceptor लगाएँ, और @CacheKey() व @CacheTTL() से उसे tune करें।
import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager';
import { UseInterceptors } from '@nestjs/common';
@UseInterceptors(CacheInterceptor)
@CacheTTL(300_000) // 5 minutes, in milliseconds (cache-manager v5+)
@Get()
findAll() {
return this.usersService.findAll();
}Redis cache
Cache module को globally register करें, फिर @keyv/redis जैसे store package से store को Redis पर बदलें।
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';
CacheModule.registerAsync({
isGlobal: true,
useFactory: async () => ({
stores: [createKeyv('redis://localhost:6379')],
ttl: 60_000,
}),
})त्वरित जाँच
त्वरित जाँच: TTL के भीतर दूसरी identical request पर `@UseInterceptors(CacheInterceptor)` वाले GET route का क्या होता है?
- handler फिर चलता है और cache overwrite करता है
- handler चलाए बिना cached response लौटता है
- हमेशा 304 लौटता है
Answer
handler चलाए बिना cached response लौटता है — cache hit handler को छोड़ देता है। सिर्फ़ GET responses अपने आप cache होते हैं।