Redis와 Node.js 연동하기 샘플 updated_at: 2024-12-15 04:02

Redis와 연동하기

아래는 다양한 연동 방식 들입니다.

sample 1

node ver 22 에서 테스트 성공

import 'dotenv/config';
import redis from 'redis';

const redisClient = redis.createClient({
  url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`,
  password: process.env.REDIS_AUTH,
  database: process.env.REDIS_DATABASE,
});


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

(async () => {
  try {
    await redisClient.connect();
    console.log('Successfully connected to Redis!');
  } catch (err) {
    console.error('Could not connect to Redis:', err);
  }
})();


export async function history(historyKey) {
  // Ensure the client is connected before trying to use it
  if (!redisClient.isOpen) {
    console.log('Redis client is not connected.');
    return;
  }
  try {
    const historyJson = await redisClient.lRange(historyKey, -10, -1);
    const history = historyJson.map(item => JSON.parse(item));
    console.log(history); // To see the output
    return history;
  } catch (err) {
    console.error('Error fetching history from Redis:', err);
  }
}


// Example of how to call the async function
(async () => {
  await history('history:test:identifire');
})();

sample 2

const redis = require('redis');
const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
   return_buffers: false,
   password: process.env.REDIS_AUTH,
   db: process.env.REDIS_DATABASE,
   retry_strategy: (options) => {
    if (options.error === null || options.error.code === 'ECONNREFUSED') {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      // return;
      return 1000; // retry after 1 sec
    }
  }
});

sample 3

require('dotenv').config();
const redis = require('redis');

const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
   return_buffers: false,
   password: process.env.REDIS_AUTH,
   db: process.env.REDIS_DATABASE,
   retry_strategy: (options) => {
    if (options.error === null || options.error.code === 'ECONNREFUSED') {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      // return;
      return 1000; // retry after 1 sec
    }
  }
});

client.lpush(['lpushTest', 'lpush test input'], () => {});
client.set(['setkey', 'setkey test input'], () => {});

sample 3

require('dotenv').config();
const redis = require('redis');

const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
  return_buffers: false,
  password: process.env.REDIS_AUTH,
  db: process.env.REDIS_DATABASE,
  retry_strategy: (options) => {
    if (options.error === null || options.error.code === 'ECONNREFUSED') {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      // return;
      return 1000; // retry after 1 sec
    }
  }
});

client.lrange('lpushTest', 0, -1, (err, data) => {
  if (err) { console.log(err); }
  console.log(data);
});

client.get('setkey', (err, data) => {
  if (err) { console.log(err); }
  console.log(data);
});

sample 4

require('dotenv').config();
const redis = require('redis');
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const path = require('path');

const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
  return_buffers: false,
  password: process.env.REDIS_AUTH,
  db: process.env.REDIS_DATABASE,
  retry_strategy: (options) => {
    if (options.error === null || options.error.code === 'ECONNREFUSED') {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      // return;
      return 1000; // retry after 1 sec
    }
  }
});

// app.use('/public', express.static('public'));
app.use(express.static(path.join(__dirname, '/public')));
// app.get('/', (req, res) => {
//    // res.send('Welcome To Node Project');
//    res.sendFile(path.join(__dirname, '/public/index.html'));
// });

app.route('/chat')
  .get((req, res) => {
    res.sendFile(path.join(__dirname, '/public/chat.html'));
  })
  .post((req, res) => {
    // res.send('Add a book');
  });

io.on('connection', (socket) => {
  console.log('a user connected');

  client.lrange('chatting.simple', 0, -1, (err, data) => {
    if (err) { console.log(err); }
    console.log('chatting.simple', data);
    // io.emit('messages', data);
    socket.emit('messages', data);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('message', (msg) => {
    client.lpush(['chatting.simple', msg], () => {});

    // io 는 모든 사람에게 보낼때 (메시지를 보내는 사람 포함)
    io.emit('message', msg);
  });
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

chat.html

<html>
  <head></head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
  var socket = io();

  $('form').submit(function(e) {
    e.preventDefault(); // prevents page reloading
    socket.emit('message', $('#m').val());
    $('#m').val('');
    return false;
  });

  socket.on('message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });

  socket.on('messages', function(msgs){
    msgs.reverse().forEach(msg => {
      $('#messages').append($('<li>').text(msg));
    });
    console.log('aaa', msgs);
  });
});
</script>

  </body>
</html>

sample5

require('dotenv').config();
const redis = require('redis');
const express = require('express')
const app = express();
const http = require('http').createServer(app);
const path = require('path');

const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
  return_buffers: false,
  password: process.env.REDIS_AUTH,
  db: process.env.REDIS_DATABASE,
  retry_strategy: (options) => {
    if (options.error === null || options.error.code === 'ECONNREFUSED') {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      // return;
      return 1000; // retry after 1 sec
    }
  }
});

const rSub = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST, {
  return_buffers: false,
  password: process.env.REDIS_AUTH,
  db: process.env.REDIS_DATABASE
});

rSub.subscribe('testpub'); // 추후 이곳에서 모두 처리

rSub.on('message', (channel, message) => {
  console.log(channel, message);
})

app.use(express.static(path.join(__dirname, '/public')));

// http://localhost:3000/subscribe?message=this is my message
app.route('/subscribe')
  .get((req, res) => {
    const mymessage = req.query.message;
    res.sendFile(path.join(__dirname, '/public/subscribe.html'));
    if (mymessage) {
      client.publish('testpub', mymessage);
    }
  })

http.listen(3000, () => {
  console.log('listening on *:3000');
});
평점을 남겨주세요
평점 : 2.5
총 투표수 : 1

질문 및 답글