๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ‘จ‍๐Ÿ’ป web.dev/node

Node.js ์„œ๋ฒ„์— Redis ์ ์šฉํ•˜๊ธฐ

by HandHand 2022. 5. 28.

๐Ÿ“Œ ๋„์ž… ๊ณ„๊ธฐ

์ด์ „์— ์‚ฌ์ด๋“œ ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ refresh token ๊ฐ’์„ redis ๋ฅผ ํ†ตํ•ด ๊ด€๋ฆฌํ•˜๊ธฐ๋กœ ํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค.

์„œ๋ฒ„๊ฐ€ ๋น„์ •์ƒ์ ์œผ๋กœ ์ข…๋ฃŒ๋  ์‹œ์—๋„ token ๊ฐ’์„ ์œ ์ง€ ํ•ด์ฃผ๊ธฐ ์œ„ํ•จ์ด์—ˆ๋Š”๋ฐ

Node.js ์„œ๋ฒ„์— Redis ๋ฅผ ์—ฐ๋™ํ•œ ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ๊ธ€์„ ๋‚จ๊น๋‹ˆ๋‹ค.

 

๐Ÿ“Œ ํ”„๋กœ์ ํŠธ ์ ์šฉ

1๏ธโƒฃ  ๋กœ์ปฌ ํ™˜๊ฒฝ์— redis ์„ค์น˜

๋จผ์ € redis ๋ฅผ ๋กœ์ปฌ ํ™˜๊ฒฝ์— ์„ค์น˜ ํ•ด์ค€ ๋‹ค์Œ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. (mac os ๊ธฐ์ค€)

$ brew install redis
$ brew services start redis

2๏ธโƒฃ  redis ํŒจํ‚ค์ง€ ์„ค์น˜

$ npm i redis

3๏ธโƒฃ  redis client ์ •์˜ํ•˜๊ธฐ

์ด์ œ express ์•ฑ์— redis ๋ฅผ ์„ค์ •ํ•˜์—ฌ ์บ์‹ฑ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

๋จผ์ € ์ „์—ญ์—์„œ ์ธ์Šคํ„ด์Šค๋กœ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํด๋ž˜์Šค ํ˜•ํƒœ๋กœ redisClient ๋ฅผ ์ •์˜ ํ•ด์ค๋‹ˆ๋‹ค.

๋˜ํ•œ ๊ธฐ์กด์˜ redis ๋Š” ์ฝœ๋ฐฑ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ฐ’์„ ์ฝ๊ธฐ ๋•Œ๋ฌธ์— Promise ๋ฅผ ํ™œ์šฉํ•ด์„œ

async await ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

// redis/index.js

const redis = require('redis');

class RedisClient {
  constructor() {
    this.client = redis.createClient(6379);
  }

  get endpoint() {
    return this.client;
  }

  setValue(key, value) {
    this.client.set(key, value);
  }

  async getValue(key) {
    return new Promise((resolve, reject) => {
      this.client.get(key, (err, value) => {
        if (err) reject(err);
        resolve(value);
      });
    });
  }
}

const redisClient = new RedisClient();
module.exports = redisClient;

 

์‚ฌ์šฉํ•˜๋Š” ์ชฝ์—์„œ๋Š” redisClient ๋ฅผ import ํ•œ ๋’ค ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ˜ธ์ถœํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

// ๊ฐ’ ์„ค์ •ํ•˜๊ธฐ
redisClient.setValue(user.id, refreshToken);

// ๊ฐ’ ์กฐํšŒํ•˜๊ธฐ
await redisClient.getValue(userID);

 

๐Ÿ“Œ ์ฐธ๊ณ  ์ž๋ฃŒ

MacOS์—์„œ Redis ์„ค์น˜ ๋ฐ ์‹คํ–‰

NodeJS and Redis Example

๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€