반응형
라이브러리 설치
npm i redis
Redis 연결
// src/config/redis/redis.service.ts
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { createClient, RedisClientType } from 'redis';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class RedisService implements OnModuleInit, OnModuleDestroy {
private client: RedisClientType;
constructor(private configService: ConfigService) {}
async onModuleInit() {
this.client = createClient({
url: `redis://${this.configService.get(
'REDIS_USERNAME',
)}:${this.configService.get('REDIS_PASSWORD')}@${this.configService.get(
'REDIS_HOST',
)}:${this.configService.get('REDIS_PORT')}/0`,
// url: `redis://${this.configService.get(
// 'REDIS_HOST',
// )}:${this.configService.get('REDIS_PORT')}`,
// password: this.configService.get('REDIS_PASSWORD'),
});
this.client.on('error', (error) => console.error(`Redis Error: ${error}`));
await this.client.connect();
console.log('Connected to Redis');
}
Redis Cloud에 연결할 땐 USERNAME 없이도 가능하지만 aws 등에서 연결할 땐 USERNAME도 작성을 해줘야 된다.
Redis CRUD
...
async onModuleDestroy() {
await this.client.quit();
}
async setRefreshToken(userId: string, token: string): Promise<void> {
await this.client.set(`refresh_token:${userId}`, token, {
EX: 60 * 60 * 24 * 7, // 7일 유효기간
});
}
async getRefreshToken(userId: string): Promise<string | null> {
return await this.client.get(`refresh_token:${userId}`);
}
async removeRefreshToken(userId: string): Promise<void> {
await this.client.del(`refresh_token:${userId}`);
}
...
반응형
'내일배움캠프 > TIL' 카테고리의 다른 글
| NPM 모듈 업데이트 (0) | 2024.01.02 |
|---|---|
| 동적 라우트 에러 (1) | 2023.12.30 |
| TIL. [Nest.JS] RESE Client & nodemon 설정 (1) | 2023.12.27 |
| TIL. RedisClient & Server 설정 (0) | 2023.12.13 |
| [뉴스피드 프로젝트] passport-kakao (0) | 2023.11.24 |
