Update your root docker-compose.yml to include a Redis container:
1
2
3
4
5
6
services:
redis:
image: redis:7-alpine
container_name: redis
ports:
- "6379:6379"
Make sure product-service depends on it:
1
2
3
4
5
6
7
8
9
10
product-service:
build: ./product-service
ports:
- "3002:3002"
environment:
- MONGO_URL=mongodb://mongo:27017/productdb
- REDIS_URL=redis://redis:6379
depends_on:
- mongo
- redis
Inside product-service:
1
npm install ioredis
Inside product-service/src/config/redis.js:
1
2
3
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
module.exports = redis;
Load REDIS_URL=redis://redis:6379 from .env.
Here’s how to cache GET /products:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const redis = require('../config/redis');
const Product = require('../models/Product');
// GET /products
const getAllProducts = async (req, res) => {
try {
// Check cache first
const cached = await redis.get('products');
if (cached) {
return res.status(200).json(JSON.parse(cached));
}
// If not cached, query DB
const products = await Product.find();
// Cache result for 1 hour
await redis.set('products', JSON.stringify(products), 'EX', 3600);
res.status(200).json(products);
} catch (err) {
res.status(500).json({ message: 'Server error' });
}
};
Update or delete actions must clear or refresh the cache:
1
2
// After update/delete:
await redis.del('products');
Or, if updating a specific product:
1
await redis.del(`product:${productId}`);
For GET /products/:id, cache per product:
1
2
3
4
5
const cached = await redis.get(`product:${id}`);
if (cached) return res.json(JSON.parse(cached));
const product = await Product.findById(id);
await redis.set(`product:${id}`, JSON.stringify(product), 'EX', 3600);