[NodeJs] Redis와 연동하기

[NodeJs] Redis와 연동하기 updated_at: 2024-01-31 17:50

Redis와 연동하기

sample 1

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 2

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>

sample 5

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

질문 및 답글