DEV Community

Cover image for Create Cache Memory using Redis in Express JS
Deepak Jaiswal
Deepak Jaiswal

Posted on

2 2

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay