Redis Guide
Redis is an in-memory data store perfect for caching, session management, and real-time features.
Add Redis to Your Project
xacos create:redisConfiguration
Configure Redis connection in .env:
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0Basic Operations
import { redisClient } from './config/redis';
// String operations
await redisClient.set('key', 'value');
const value = await redisClient.get('key');
// Set with expiration (in seconds)
await redisClient.setex('key', 3600, 'value');
// Hash operations
await redisClient.hset('user:1', 'name', 'John');
const name = await redisClient.hget('user:1', 'name');
// List operations
await redisClient.lpush('queue', 'task1');
const task = await redisClient.rpop('queue');Caching Pattern
async function getCachedUser(id: string) {
const cached = await redisClient.get(`user:${id}`);
if (cached) {
return JSON.parse(cached);
}
const user = await database.findUser(id);
await redisClient.setex(
`user:${id}`,
3600,
JSON.stringify(user)
);
return user;
}Common Use Cases
- API response caching
- Session storage
- Rate limiting
- Leaderboards
- Pub/Sub messaging
- Job queues