To retrieve cached data from Redis in a Node.js application, you can follow these steps using Express and Redis:
1. Install Dependencies: By using npm install express redis
2. Basic Setup:
- Initialize a Redis client.
- Connect to Redis.
- Create an Express route to fetch cached data by key.
3. Implementation:
// Initialize the Redis client
const client = createClient();
client.on('error', (err) => {
console.error('Redis Client Error', err);
});
// Connect to Redis
client.connect()
.then(() => console.log('Connected to Redis'))
.catch((err) => console.error('Error connecting to Redis:', err));
// Initialize the Express app
const app = express();
// Route to get a cached value by key from Redis
app.get('/get-cache/:key', async (req, res) => {
const { key } = req.params;
try {
// Check if the Redis client is connected
if (!client.isOpen) await client.connect();
// Get the cached value from Redis
const value = await client.get(key);
if (value !== null) {
res.send(`Cached value for key is "${key}": ${value}`);
} else {
res.send(`No cached value found for key is "${key}"`);
}
} catch (err) {
console.error('Error retrieving cache:', err);
res.status(500).send('Server error');
}
});
// Start the Express server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
4. How it works:
- Use client.get(key) to retrieve cached values.
- If the key exists in Redis, it returns the cached value.
- If the key does not exist, it responds with a message saying "No cached value found."