Working with Redis
Use Redis for caching and sessions. Learn Redis data structures.
Working with Redis
What is Redis?
Redis is an in-memory data store. Super fast because data lives in RAM.
**Use cases:** - Caching - Sessions - Real-time analytics - Pub/Sub messaging - Rate limiting
Setup
```bash npm install redis ```
```javascript const redis = require('redis');
const client = redis.createClient({ host: 'localhost', port: 6379 });
await client.connect(); ```
Basic Operations
```javascript await client.set('key', 'value');
const value = await client.get('key');
await client.setEx('key', 3600, 'value');
await client.del('key');
const exists = await client.exists('key');
await client.incr('counter'); ```
Caching Pattern
```javascript async function getUser(id) { const cacheKey = `user:${id}`; const cached = await client.get(cacheKey); if (cached) { return JSON.parse(cached); } const user = await User.findById(id); await client.setEx(cacheKey, 3600, JSON.stringify(user)); return user; } ```
Lists
```javascript await client.rPush('queue', 'task1'); await client.rPush('queue', 'task2');
const task = await client.lPop('queue');
const length = await client.lLen('queue'); ```
Sets
```javascript await client.sAdd('tags', 'nodejs'); await client.sAdd('tags', 'redis');
const isMember = await client.sIsMember('tags', 'nodejs');
const members = await client.sMembers('tags'); ```
Hashes
```javascript await client.hSet('user:123', 'name', 'John'); await client.hSet('user:123', 'email', 'john@example.com');
const name = await client.hGet('user:123', 'name');
const user = await client.hGetAll('user:123'); ```
Key Takeaway
Redis is fast in-memory storage. Use for caching, sessions, queues. Data structures: strings, lists, sets, hashes. Set expiration to save memory.