DEV Community

Cover image for Create Cache Memory using Redis in Express JS
Sandeep
Sandeep

Posted on

Create Cache Memory using Redis in Express JS

hello all developers we create a Redis store to make server to best response to the client. Redis can maximize the response time of fetching data through server like express.

so , Redis is a super fast and efficient in-memory, key–value cache (hashing the data) and store. It’s also known as a data structure server, as the keys can contain strings, lists, sets, hashes and other data structures. keys will be unique.

npm install redis

const redis = require('redis');
//by default port 6379 and host localhost or 127.0.0.1 
const client = redis.createClient();
Enter fullscreen mode Exit fullscreen mode
const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
  console.log('Connected!');
});
Enter fullscreen mode Exit fullscreen mode

so make sure you can install redis in your system.

const redis = require('redis');
const client = redis.createClient();
const axios = require('axios');
const express = require('express');

const app = express();
const USERS_API = 'Your Api Url';

app.get('/cached-users', async (req, res) => {

    const data=await client.get('users')


   try{
      if (data) {
        console.log('Users retrieved from Redis storage');
        res.status(200).send(JSON.parse(data));
      } else {
        axios.get(`${USERS_API}`).then(function (response) {
          const users = response.data;
          //client.setEx('key',seconds,data)
          client.setEx('users', 400, JSON.stringify(users));
          console.log('Users retrieved from the API');
          res.status(200).send(users);
        });
      }
    });
  } catch (err) {
    res.status(500).send({ error: err});
  }
});

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`Server started at port: ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Image description

Discussion (0)