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 Node.js project:
mkdir redis-api
cd redis-api
npm init -y
- Install Required Packages:
npm install express redis
Example Code:
- 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:
Setup Redis Client: redis.createClient() creates a Redis client to connect to the Redis server. It listens for any connection errors.
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.
- Start Server: The server listens on port 3000 and logs a message when it starts.
Running the Server:
- Start Redis Server: Make sure Redis is running. You can start it with:
redis-server
- Run the Node.js Server:
node app.js
- 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.