NestJS 캐시 설치
npm install cache-manager
npm install -D @types/cache-manager
io-redis 설치
npm install cache-manager-ioredis --save
npm install -D @types/cache-manager-ioredis
앱모듈에 레디스 등록하기
import { CacheModule, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [CacheModule.register({
store: redisStore,
// clusterConfig: {
// nodes: [{
// port: 6379,
// host: `127.0.0.1`,
// }]
// },
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
})],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
.env 환경변수
#Redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_DB=
REDIS_PASS=
REDIS_PRIFIX=
컨트롤러에서 확인하기
import { CACHE_MANAGER, Controller, Get, Inject, Query } from '@nestjs/common';
import { Cache } from 'cache-manager'
@Controller()
export class AppController {
constructor(
@Inject(CACHE_MANAGER) private cacheManager: Cache
) {}
@Get("/cache")
async getCache(@Query('id') id : string ): Promise<string> {
const savedTime = await this.cacheManager.get(id)
if( savedTime )
return "saved time : " + savedTime
const now = new Date().getTime()
await this.cacheManager.set(id,now,{ ttl:600 });
return "save new time : " + now
}
}
localhost:3000/cache?id=1로 접속하고 레디스 확인하기
이제 pub/sub을 공부해야겠다.
'Server > DB' 카테고리의 다른 글
MySQL) JSON_SEARCH 데이터 추출하기 (0) | 2022.04.15 |
---|---|
console.time()으로 DB 접속시간 확인하기 (0) | 2022.04.04 |
Prisma multiple database connection (0) | 2022.03.17 |
Mysql) Datetime Timestamp 차이 (0) | 2022.03.16 |
Sequel Pro 연결 오류 (0) | 2022.03.16 |