4. Nest.js 광부왕 게임 서버 Redis 설정 [캐시 데이터]

2023. 3. 2. 20:52프로젝트/게임 서버 - Nest.js

- 캐시 데이터

DB : Redis

 

사용 이유 : 입출력 속도가 빠르고 서버 스케일 아웃이 발생하면 동일한 캐시 데이터를 사용 할 수 없어 한 곳에서 관리하기 용이


1. 모듈, 서비스 생성

nest g mo redis
nest g s redis

redis.module.ts

redis.service.ts

파일이 생성된다. 


2. 사용 Redis 명령어

아래 명령어를 사용 할 예정이다.

 

ZRANGE : 순위를 저장 한 key 들을 가져오는 명령어 

* WITHSCORES 옵션을 넣으면 순위와 함께 점수가 같이 출력 된다.

start :  순위 시작 값 ( 0부터 시작 )end : 마지막 순위 값 ( -1일 경우 전체 )

사용범위 : 

  •  회사 주간 순위를 확인 

ZSCORE : zrange에 저장된 순위 중 검색하는 key 의 순위 검색하는 명령어

사용범위 :

  •  검색하는 회사 주간 순위 확인

 

ZADD : 순위를 저장하는 value를 증가하는 명령어

사용범위 : 

  • 회사 주간 점수 상승

 

EXPIRE : Redis에 저장하는 키에 유효 시간 설정 명령어

사용범위 : 

  • 소켓, 주간 랭킹 유효 시간이 지나면 자동 제거

 

DEL : 저장된 key 제거 명령어

사용범위 : 

  • 유저 로그 아웃 시 소켓 제거

 

SET : key / value 저장 명령어

사용범위 : 

  • 소켓, 유저 정보 저장

 

GET : value 검색 명령어

사용범위 : 

  • 소켓, 유저 정보 확인

3. redis.service.ts 작성

import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';
@Injectable()
export class RedisService {
  redis: Redis = new Redis(process.env.REDIS);

  async zrange(data: {
    name: string;
    start: number;
    end: number;
    optionStatus: boolean;
  }) {
    const { name, start, end, optionStatus } = data;
    if (optionStatus) {
      return await this.redis.zrange(name, start, end, 'WITHSCORES');
    } else {
      return await this.redis.zrange(name, start, end);
    }
  }

  async zscore(data: { name: string; index: string }) {
    const { name, index } = data;
    return await this.redis.zscore(name, index);
  }

  async zadd(data: { name: string; point: number; index: string }) {
    const { name, point, index } = data;
    await this.redis.zadd(name, point, index);
  }

  async expire(data: { name: string; time: number }) {
    const { name, time } = data;
    await this.redis.expire(name, time);
  }

  async del(data: string) {
    await this.redis.del(data);
  }

  async set(data: { name: string; content: string }) {
    const { name, content } = data;
    await this.redis.set(name, content);
  }

  async get(data: string) {
    return await this.redis.get(data);
  }
}

 

728x90
반응형