Redis Comprehensive Guide: From Installation to Express Integration

AKRAM BOUTZOUGA
3 min readDec 6, 2024

--

I’ve created a comprehensive guide covering some of the interesting topics you’ll need as dev you could save it as a cheat sheet, with practical examples and best practices. The guide progresses from basic Redis setup to more complex integrations with Express and queue systems. Each section includes working code examples that you can adapt to your needs.

1. Setting Up Redis Server

Installation:

# On Ubuntu/Debian
sudo apt-get update
sudo apt-get install redis-server

# On macOS using Homebrew
brew install redis

# On Windows
# Download the Windows Subsystem for Linux (WSL) and follow Ubuntu instructions

Starting the Server:

# Start the Redis server
redis-server

# Verify the server is running
redis-cli ping
# Should return "PONG"

2. Basic Redis CLI Operations

# Start Redis CLI
redis-cli

# Basic SET and GET
SET user:1 "John Doe"
GET user:1

# Lists
LPUSH mylist "first"
RPUSH mylist "last"
LRANGE mylist 0 -1

# Sets
SADD myset "unique1"
SADD myset "unique2"
SMEMBERS myset

# Expiration
SET token "12345" EX 3600 # Expires in 1 hour

3. Redis with Node.js

Setup:

npm install redis

Basic Operations:

const redis = require('redis');
const client = redis.createClient();

// Handle connection events
client.on('connect', () => {
console.log('Connected to Redis');
});

client.on('error', (err) => {
console.log('Redis Client Error', err);
});

// Basic operations
async function basicOperations() {
await client.connect();

// String operations
await client.set('key', 'value');
const value = await client.get('key');

// Lists
await client.lPush('mylist', ['value1', 'value2']);

// Sets
await client.sAdd('myset', ['member1', 'member2']);
}

4. Working with Hash Values

async function hashOperations() {
// Set multiple hash fields
await client.hSet('user:1', {
name: 'John',
email: 'john@example.com',
age: '30'
});

// Get specific field
const name = await client.hGet('user:1', 'name');

// Get all fields
const userData = await client.hGetAll('user:1');

// Delete field
await client.hDel('user:1', 'age');
}

5. Handling Async Operations

// Using async/await
async function handleAsync() {
try {
await client.set('key', 'value');
const result = await client.get('key');
console.log(result);
} catch (error) {
console.error('Error:', error);
}
}

// Using Promise chains
client.set('key', 'value')
.then(() => client.get('key'))
.then(result => console.log(result))
.catch(error => console.error('Error:', error));

6. Implementing Kue Queue System

const kue = require('kue');
const queue = kue.createQueue();

// Create a job
function createJob(data) {
const job = queue.create('email', {
title: 'Welcome Email',
to: data.email,
template: 'welcome'
});

job.save(err => {
if (err) console.error('Job save error:', err);
});
}

// Process jobs
queue.process('email', (job, done) => {
sendEmail(job.data, done);
});

function sendEmail(data, done) {
// Email sending logic
done();
}

7. Basic Express App with Redis

const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient();

app.use(express.json());

// Connect to Redis
await client.connect();

// Cache middleware
async function cache(req, res, next) {
const key = req.originalUrl;
const data = await client.get(key);

if (data) {
return res.json(JSON.parse(data));
}
next();
}

// Routes
app.get('/api/users/:id', cache, async (req, res) => {
const userData = await fetchUserData(req.params.id);
await client.set(req.originalUrl, JSON.stringify(userData), {
EX: 3600 // Cache for 1 hour
});
res.json(userData);
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

8. Express App with Redis and Queue

const express = require('express');
const redis = require('redis');
const kue = require('kue');

const app = express();
const client = redis.createClient();
const queue = kue.createQueue();

app.use(express.json());

// Connect to Redis
await client.connect();

// Example: User registration endpoint
app.post('/api/users', async (req, res) => {
try {
// Store user in database
const user = await createUser(req.body);

// Cache user data
await client.hSet(`user:${user.id}`, user);

// Create welcome email job
const job = queue.create('welcome-email', {
title: 'Welcome Email',
userId: user.id,
email: user.email
});

job.save(err => {
if (err) console.error('Queue error:', err);
});

res.status(201).json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});

// Process welcome emails
queue.process('welcome-email', async (job, done) => {
try {
await sendWelcomeEmail(job.data);
done();
} catch (error) {
done(error);
}
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

Best Practices and Tips

  1. Always handle Redis connection errors
  2. Use appropriate expiration times for cached data
  3. Implement retry mechanisms for failed queue jobs
  4. Monitor Redis memory usage
  5. Use Redis transactions when needed
  6. Implement proper error handling
  7. Consider using Redis Pub/Sub for real-time features
  8. Use Redis clustering for scalability

--

--

AKRAM BOUTZOUGA
AKRAM BOUTZOUGA

Written by AKRAM BOUTZOUGA

Junior Calisthenics Engineer, Ai Enthusiast. Coding and Flexing! 💻💪

No responses yet