티스토리 뷰

IT 한스푼

Node.js와 Express를 이용한 서버 캐싱 구현 방법

예술하는 개발자 최씨 2023. 3. 27. 16:57
반응형

 

Node.js와 Express를 이용하여 서버를 개발할 때, 캐싱을 구현하여 서버의 응답 속도를 높일 수 있습니다.

이번 글에서는 Node.js와 Express를 이용한 서버 캐싱 구현 방법에 대해 알아보겠습니다.

 

1. Node-cache 모듈을 이용한 메모리 캐싱 구현 방법

 

Node-cache는 Node.js에서 사용할 수 있는 메모리 캐시 모듈입니다. Node-cache를 이용하여 캐시를 구현하면, 서버의 응답 속도를 높일 수 있습니다.

먼저, Node-cache 모듈을 설치합니다.

 

npm install node-cache --save

 

다음으로, Node-cache 모듈을 사용하여 캐시를 구현합니다. 아래 예제 코드는 Node-cache 모듈을 이용하여 getUser 함수의 결과를 캐싱하는 방법을 보여줍니다.

 

const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60, checkperiod: 120 });

function getUser(userId, callback) {
  const cacheKey = `user-${userId}`;
  const cachedUser = cache.get(cacheKey);
  if (cachedUser) {
    console.log(`Cache hit: ${userId}`);
    callback(null, cachedUser);
  } else {
    console.log(`Cache miss: ${userId}`);
    // fetch user data from database or external API
    // ...
    const userData = { name: 'John Doe', email: 'john.doe@example.com' };
    // cache user data
    cache.set(cacheKey, userData);
    callback(null, userData);
  }
}

 

위 예제 코드에서는 getUser 함수에서 Node-cache 모듈을 이용하여 캐시를 구현하고 있습니다. cacheKey 변수에는 캐시의 키값을 지정합니다. cache.get(cacheKey) 메소드를 이용하여 캐시에 데이터가 있는지 확인하고, 캐시에 데이터가 있다면 cachedUser 변수에 저장합니다. 캐시에 데이터가 없다면 getUser 함수는 데이터를 가져오고, 데이터를 cache.set(cacheKey, userData) 메소드를 이용하여 캐싱합니다.

 

 

2. HTTP 응답 헤더를 이용한 서버 캐싱 구현 방법

 

HTTP 응답 헤더를 이용하여 서버 캐싱을 구현할 수도 있습니다. 예를 들어, Cache-Control 헤더를 이용하여 캐싱을 제어할 수 있습니다. 아래 예제 코드는 Cache-Control 헤더를 이용하여 캐시를 구현하는 방법을 보여줍니다.

 

app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  const userData = { name: 'John Doe', email: 'john.d

 

편리한 캐싱 기능은 서버 성능을 향상시키는 데 큰 도움을 줍니다. Node.js에서도 Express와 같은 프레임워크를 사용하여 간단하게 캐싱을 구현할 수 있습니다. 이번에는 Node.js Express에서 캐싱을 하는 방법에 대해 알아보겠습니다.

 

 

3. Express에서 캐싱 기능 사용하기

Express에서 캐싱을 구현하는 가장 간단한 방법 중 하나는 memory-cache 모듈을 사용하는 것입니다. memory-cache 모듈은 메모리에 캐시 데이터를 저장하므로, 서버를 재시작하면 모든 캐시가 삭제됩니다.

다음은 memory-cache 모듈을 사용하여 간단한 캐싱 미들웨어를 만드는 예시 코드입니다.

 

const cache = require('memory-cache');

function cacheMiddleware(duration) {
  return (req, res, next) => {
    const key = '__express__' + req.originalUrl || req.url;
    const cachedBody = cache.get(key);

    if (cachedBody) {
      res.send(cachedBody);
      return;
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        cache.put(key, body, duration * 1000);
        res.sendResponse(body);
      };
      next();
    }
  };
}

이 미들웨어는 지정된 시간(duration)동안 캐싱하며, 요청이 들어올 때마다 캐시에 데이터가 있는지 확인합니다. 캐시에 데이터가 있으면 해당 데이터를 바로 반환하고, 캐시에 데이터가 없으면 원래의 요청을 처리하고 응답을 캐싱합니다.

이제 이 캐싱 미들웨어를 Express 앱에 적용해보겠습니다.

 

const express = require('express');
const cache = require('memory-cache');
const app = express();

function cacheMiddleware(duration) {
  return (req, res, next) => {
    const key = '__express__' + req.originalUrl || req.url;
    const cachedBody = cache.get(key);

    if (cachedBody) {
      res.send(cachedBody);
      return;
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        cache.put(key, body, duration * 1000);
        res.sendResponse(body);
      };
      next();
    }
  };
}

// 라우터를 등록합니다.
app.get('/', cacheMiddleware(10), (req, res) => {
  res.send('Hello World!');
});

// 서버를 실행합니다.
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

 

위 코드에서 / 루트 경로에 캐싱 미들웨어를 적용했습니다. duration 인자로 10을 넘겨주면 해당 경로의 응답이 10초 동안 캐시됩니다.

 

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함