본문 바로가기

개발

[Redis] node.js에서 Redis 캐싱

🍏 redis 설치

1️⃣ Redis 서버 설치

https://yun000.tistory.com/301

 

[Redis] Window에 Reids 설치

1️⃣ 설치 아래의 링크에서 Redis-x64-3.0.504.msi를 다운받는다https://github.com/microsoftarchive/redis/releases Releases · microsoftarchive/redisRedis is an in-memory database that persists on disk. The data model is key-value, but many d

yun000.tistory.com

 

2️⃣ Node.js에서 Redis 서버에 접속하기 위한 클라이언트 라이브러리 설치

npm i redis

 

🍏 Redis 클라이언트 초기화 및 연결 코드

utils/redisClient.js

const { createClient } = require('redis');

const redisClient = createClient(); // 기본: localhost:6379
//const redisClient = createClient({ url: REDIS_URL넣기 });


redisClient.on('error', (err) => {
  console.error('Redis Client Error:', err);
});

(async () => {
  await redisClient.connect();
  console.log(' Redis 연결 성공');
})();

module.exports = redisClient;

 

 

🍏 Redis 캐싱 적용 기준

- 실시간으로 조회해야 하는 데이터가 아닌 경

- 읽기가 빈번하고 변경이 드문 데이터

- 계산 비용이 크거나 느린 쿼리

- 데이터 크기가 너무 크지 않은 경우

 

+) 메모리 대비 이득이 큰 데이터가 좋다.

Redis는 인메모리 캐시이기 때문에 데이터 용량이 너무 클 경우 메모리 부족할 수 있음

 

🍏 Redis 명령어

const redisClient = require('../utils/redisClient'); //Redis 클라이언트 모듈 불러오기
캐시 값 저장 await redisClient.setEx(key, seconds, value) key, value 저장 + seconds 동안 유지
캐시 값 저장2 await redisClient.set(key, value) 만료 시간 없이 key, value 저장
값 가져오기 const value = await redisClient.get(key) key에 저장된 value 가져오기
키 삭제 await redisClient.del(key) key 삭제
여러 키 한번에 삭제 await redisClient.del(key1, key2, key3) 복수 개 키 삭제
키 존재 여부 확인 const exists = await redisClient.exists(key) 존재하면 1, 없으면 0 반환
만료시간 설정 await redisClient.expire(key, seconds) 이미 저장된 key에 만료시간 추가
TTL 조회 const ttl = await redisClient.ttl(key) key의 남은 TTL(Time To Live) 초 조회
모든 키 조회 const keys = await redisClient.keys('*') keys('campus:*') 처럼 사용 가능
캐시 비우기 await redisClient.flushAll() 모든 데이터 삭제

 

 

🍏 Redis 적용 예시

ex) UI 목록, 사용자 프로필 정보 등..

const redisClient = require('../utils/redisClient'); //Redis 클라이언트 모듈 불러오기

router.get('/', async (req, res) => {
  const cacheKey = 'flight:airportList';

  try {
    const cached = await redisClient.get(cacheKey);
    if (cached) {
      console.log('[flight:airport] Redis cache hit!');
      return res.json(JSON.parse(cached));
    }

    const result = await fetchOpenApi('/AirportCodeList/getAirportCodeList', {
      numOfRows: 1360,
      pageNo: 1,
    });

    await redisClient.setEx(cacheKey, 86400, JSON.stringify(result.data)); // 1일 캐시
    res.json(result.data);
  } catch (error) {
    console.error('[light:airport 조회 실패]', error.message);
    res.status(error.response?.status || 500).json({
      error: error.response?.data || 'Internal Server Error',
    });
  }
});

 

 

🍏 Redis 적용 확인

Redis를 설치한 위치에 있는 redis-cli.exe를 실행 시킨후 아래와 같은 명령어 캐시 확인 가능

(만약 기본 설정을 따랐다면 C:\Program Files\Redis 에 설치 되어 있다.)

 

저장된 모든 캐시 키 확인 가능

keys *

 

특정 캐시 데이터 확인

get weather:latest

모든 캐시 삭제

flushall

 

'개발' 카테고리의 다른 글

[Redis] Spring Boot에서 Redis 캐싱  (0) 2025.04.19
[Redis] Window에 Reids 설치  (0) 2025.04.19
[Node.js] Node.js 기초  (0) 2025.03.28
FastAPI  (0) 2025.03.21
AWS Athena를 통해 S3 parquet 데이터 조회 (C#)  (0) 2025.03.21