npm install cache-manager
npm install --dev @types/cache-manager
npm install cache-manager-ioredis --save
npm install -g redis-cli
https://redis.com/redis-enterprise-cloud/overview/
REDIS_HOST=
REDIS_PORT=
REDIS_USERNAME=
REDIS_PASSWORD=
REDIS_TTL=100
를 채웠다.
환경변수(env)를 사용하기 위해서 config 패키지를 설치
configModule, cacheModule 설정
다른 파일에서 환경 변수 로드하기
//app.module.ts
import { CacheModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { CacheConfigService } from './config/cache.config.service';
...
@Module({
imports: [
...
ConfigModule.forRoot({ isGlobal: true }),
CacheModule.registerAsync({
isGlobal: true,
imports: [ConfigModule],
inject: [ConfigService],
useClass: CacheConfigService,
}),
...
],
...
})
//cache.config.service.ts
import {
CacheModuleOptions,
CacheOptionsFactory,
Injectable,
} from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class CacheConfigService implements CacheOptionsFactory {
constructor(private readonly configService: ConfigService) {}
createCacheOptions(): CacheModuleOptions<Record<string, any>> {
return {
store: redisStore,
host: this.configService.get<string>('REDIS_HOST'),
port: this.configService.get<number>('REDIS_PORT'),
password: this.configService.get<string>('REDIS_PASSWORD'),
username: this.configService.get<string>('REDIS_USERNAME'),
ttl: this.configService.get<number>('REDIS_TTL'),
};
}
}
캐시되지 않은 데이터에 대한 요청
1 요청이 캐시 가능한 요청인지 확인
2 요청에 대해 캐시된 데이터를 확인 , 캐시된 데이터가 없으므로 컨트롤러/서비스 등 비즈니스 로직을 실행
3 비즈니스 로직 실행 이후, 응답할 데이터를 요청된 endpoint를 기준으로 캐싱 처리
캐시된 데이터에 대한 요청
1 요청이 캐시 가능한 요청인지 확인
2 요청 엔드포인트로 캐시된 데이터를 확인,미리 캐시된 데이터가 있는 경우 비즈니스 로직을 실행하지 않고 캐시된 데이터를 곧바로 응답
캐시 가져오기 - this.cacheManager.get(key);
캐시 생성 - his.cacheManager.set(key, value);
key값 지우기- this.cacheManager.del(key);
//share-products.service.ts
import { CACHE_MANAGER } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Products } from './entities/share-products.entity';
import { Cache } from 'cache-manager';
@Injectable()
export class ProductsService {
constructor(
private readonly productsRepository: Repository<Products>,
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache
) {}
async findAll() {
const value = await this.cacheManager.get(`all-share-products`);
if (!value) {
const allProducts = await this.productsRepository.find({
relations: ['productsTradeLocation', 'productsCategory'],
});
await this.cacheManager.set(`all-share-products`, allProducts);
return allProducts;
}
return value;
}
async delete(id) {
const result = await this.productsRepository.delete(id);
await this.cacheManager.del(`all-share-products`);
return result.affected > 0;
}
}
redis-cli -u redis://name:password@host:port
