Node.js Integration
For Node.js developers, there are two main libraries: redis (official) and ioredis (feature-rich).
1. Using @redis/client
Installation
npm install redisBasic Connection
import { createClient } from 'redis';
const client = createClient({
url: 'redis://alice:password@127.0.0.1:6379'
});
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
// Perform operations
await client.set('key', 'value');
const value = await client.get('key');2. Using ioredis (Recommended for Cluster/Sentinel)
ioredis is often preferred for enterprise apps due to its robust support for pipelines, clusters, and sentinel.
Installation
npm install ioredisBasic Usage
const Redis = require('ioredis');
const redis = new Redis(); // Defaults to 127.0.0.1:6379
// Async/Await
async function testRedis() {
await redis.set('user:name', 'Pratap');
const name = await redis.get('user:name');
console.log(name);
}Pipeline (Performance Improvement)
Pipelines allow you to send multiple commands without waiting for responses individually, reducing network RTT.
const pipeline = redis.pipeline();
pipeline.set('foo', 'bar');
pipeline.del('cc');
pipeline.exec((err, results) => {
// `results` is an array of responses
});3. Real-world Implementation Example: Express Middleware Cache
const redis = new Redis();
const cacheMiddleware = async (req, res, next) => {
const key = `cache:${req.originalUrl}`;
const cachedData = await redis.get(key);
if (cachedData) {
return res.json(JSON.parse(cachedData));
}
// Override res.send to cache the response
res.sendResponse = res.json;
res.json = (body) => {
redis.set(key, JSON.stringify(body), 'EX', 3600); // Cache for 1 hour
res.sendResponse(body);
};
next();
};