Redis with Node application

To demonstrate how to use Redis in a Node.js application for handling API requests, I’ll show a simple example where Redis is used to cache the response of an API request.

Setup:

Install Redis: Make sure Redis is installed and running.
Create a new …


This content originally appeared on DEV Community and was authored by Pranav Bakare

To demonstrate how to use Redis in a Node.js application for handling API requests, I'll show a simple example where Redis is used to cache the response of an API request.

Setup:

  1. Install Redis: Make sure Redis is installed and running.

  2. Create a new Node.js project:

mkdir redis-api
cd redis-api
npm init -y
  1. Install Required Packages:
npm install express redis

Example Code:

  1. Create a file app.js with the following code:
const express = require('express');
const redis = require('redis');
const app = express();
const port = 3000;

// Connect to Redis
const redisClient = redis.createClient();

redisClient.on('error', (err) => {
    console.error('Redis error:', err);
});

// Middleware to handle JSON request bodies
app.use(express.json());

// Handle GET request to /api/data
app.get('/api/data', (req, res) => {
    const key = 'dataKey';

    // Check if data is in Redis cache
    redisClient.get(key, (err, cachedData) => {
        if (err) return res.status(500).send('Server error');

        if (cachedData) {
            console.log('Serving from Redis cache');
            return res.json(JSON.parse(cachedData));
        }

        console.log('Fetching new data');
        // Simulate data fetching
        const newData = { message: 'This is fresh data!' };

        // Store new data in Redis cache with an expiration time of 60 seconds
        redisClient.setex(key, 60, JSON.stringify(newData), (err) => {
            if (err) return res.status(500).send('Server error');

            res.json(newData);
        });
    });
});

// Start the server
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});



Explanation:

  1. Setup Redis Client: redis.createClient() creates a Redis client to connect to the Redis server. It listens for any connection errors.

  2. Check Cache: When a GET request is made to /api/data, the server first checks if the data is cached in Redis using redisClient.get().

If data is cached, it is returned to the client.

If data is not cached, the server simulates fetching new data, stores this data in Redis with redisClient.setex() (setting an expiration time of 60 seconds), and then responds to the client.

  1. Start Server: The server listens on port 3000 and logs a message when it starts.

Running the Server:

  1. Start Redis Server: Make sure Redis is running. You can start it with:

redis-server

  1. Run the Node.js Server:

node app.js

  1. Test the API:

First Request: Make a GET request to http://localhost:3000/api/data using a browser or a tool like Postman. The response will be fetched and cached in Redis.

Subsequent Requests: Making the same GET request within 60 seconds will retrieve the data from the Redis cache.

This example demonstrates how to integrate Redis caching with a Node.js API to improve performance by reducing the need to fetch data repeatedly from the source.


This content originally appeared on DEV Community and was authored by Pranav Bakare


Print Share Comment Cite Upload Translate Updates
APA

Pranav Bakare | Sciencx (2024-09-12T21:52:05+00:00) Redis with Node application. Retrieved from https://www.scien.cx/2024/09/12/redis-with-node-application/

MLA
" » Redis with Node application." Pranav Bakare | Sciencx - Thursday September 12, 2024, https://www.scien.cx/2024/09/12/redis-with-node-application/
HARVARD
Pranav Bakare | Sciencx Thursday September 12, 2024 » Redis with Node application., viewed ,<https://www.scien.cx/2024/09/12/redis-with-node-application/>
VANCOUVER
Pranav Bakare | Sciencx - » Redis with Node application. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/12/redis-with-node-application/
CHICAGO
" » Redis with Node application." Pranav Bakare | Sciencx - Accessed . https://www.scien.cx/2024/09/12/redis-with-node-application/
IEEE
" » Redis with Node application." Pranav Bakare | Sciencx [Online]. Available: https://www.scien.cx/2024/09/12/redis-with-node-application/. [Accessed: ]
rf:citation
» Redis with Node application | Pranav Bakare | Sciencx | https://www.scien.cx/2024/09/12/redis-with-node-application/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.